h是给定的带头结点的单链表,函数invertList要将h逆序。逆序应直接使用原序列中的结点。用java实现
时间: 2025-01-06 16:53:07 浏览: 34
好的,我来为您介绍如何用Java实现一个将带头结点的单链表逆序的函数invertList。
实现思路:
1. 使用三个指针:pre, cur, next
2. 从头到尾遍历链表,逐个改变结点的next指针方向
3. 最后将头结点的next指向新的头结点
以下是Java代码实现:
```java
public class LinkedList {
// 定义链表结点
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
// 逆序函数
public static ListNode invertList(ListNode h) {
if (h == null || h.next == null) return h; // 如果链表为空或只有一个结点,直接返回
ListNode pre = null; // 前一个结点
ListNode cur = h.next; // 当前结点
ListNode next = null; // 下一个结点
while (cur != null) {
next = cur.next; // 保存下一个结点
cur.next = pre; // 改变当前结点的next指向
pre = cur; // pre移动到当前结点
cur = next; // cur移动到下一个结点
}
h.next = pre; // 将头结点的next指向新的头结点
return h;
}
// 打印链表
public static void printList(ListNode h) {
ListNode cur = h.next;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
}
// 测试函数
public static void main(String[] args) {
// 创建链表: 1->2->3->4->5
ListNode head = new ListNode(0);
ListNode cur = head;
for (int i = 1; i <= 5; i++) {
cur.next = new ListNode(i);
cur = cur.next;
}
System.out.println("原链表:");
printList(head);
// 逆序链表
invertList(head);
System.out.println("逆序后:");
printList(head);
}
}
```
这段代码首先定义了一个链表结点类ListNode,然后实现了invertList函数来逆序链表。printList函数用于打印链表,main函数用于测试。
invertList函数的工作原理如下:
1. 检查链表是否为空或只有一个结点,如果是,直接返回。
2. 初始化三个指针:pre(前一个结点), cur(当前结点)和next(下一个结点)。
3. 遍历链表,对于每个结点:
- 保存下一个结点到next
- 将当前结点的next指向前一个结点pre
- 将pre移动到当前结点
- 将cur移动到下一个结点
4. 遍历结束后,将头结点的next指向pre,完成逆序。
阅读全文
相关推荐



















