剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
(来源:力扣(LeetCode))
思路:递归
(1)如果没有结点,或者只有一个结点,则直接返回,即
if (node == null || node.next == null) return node;
(2)使用递归方法,我们应该将原问题分解成小问题,再用小问题的解去构造大问题的解:
如图,想求大问题的解就要先获得节点1,获得节点1就要先获得节点2。
在原问题当中,节点1指向节点2,即node1.next = node2,
在反转链表中,节点2指向节点1,即node2.next = node1,
综合可得,node1.next.next = node1.
依次类推,可获得整个反转链表。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
思路:迭代法
我们要将整个链表反转,就需要改变节点的next指针,即
将节点1的next指针指向NULL,
将节点2的next指针指向节点1,
将节点3的next指针指向节点2,
…
所以我们需要一个pre变量来记录节点node的前一个node,并且将node反转之后,node后面那个node就会丢失,所以我们还需要一个nxt指针记录后面的node,以防丢失。
具体步骤:
(1) 将节点1的next指针指向NULL;
将三个指针都移动到下一个位置;
(2)将节点2反转指向节点1;
同样是将三个指针移动到下一个位置;
(3)将节点3的next指针指向节点2;
移动三个指针;
(4)将节点4的next指针指向节点3;
移动三个指针;
(5)将节点5的next指针指向节点4;
移动三个指针;
我们使用while循环来完成这一过程,循环结束条件是cur = null,且pre指针的初始化为NULL,cur指向头节点。
最后返回pre。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}