剑指 Offer 24. 反转链表
题目描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点
例如(见代码):
输入 [1,2,3]
输出 [3,2,1]
解法:
思路一:迭代
1. 迭代需要三个指针,previous(上一个),current(当前),next(下一个),分别按顺序指向三个节点
2. 三个指针的初始化:previous指向空节点,current指向头结点head,next指向current.next
因为current.next可能不存在,next在循环中定义,这样如果current为空就不会进入循环
3. 迭代过程
1.next指向current.next
2.cur指向pre
3.pre移动到cur位置
4.cur移动到nxt位置
null----1-------2-------3-------4-------5-----null
prev cur nxt
prev cur nxt(依次循环)
4. 当cur为空时,返回pre
详细过程见图片:
ListNode 实体
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
解题代码
class Solution {
public ListNode reverseList01(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
// 将 current 下面部分的复制一遍 然后赋值给了next
ListNode next = current.next;
// 将previous 赋值给 current 下面的部分
current.next = previous;
// 将current 赋值给 previous
previous = current;
// 将 next 赋值给 current
current = next;
}
return previous;
}
// 测试
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution24 solution24 = new Solution24();
ListNode head01 = solution24.reverseList01(head);
System.out.println(head01.val);
System.out.println(head01.next.val);
System.out.println(head01.next.next.val);
}
}