题目描述
给定一个单链表的头节点 h e a d head head,如何在 O ( 1 ) O(1) O(1) 的空间复杂度下反转链表,并返回反转后的链表头?
比如给定链表为 1 -> 2 -> 3 -> 4 -> 5
,反转后应为 5 -> 4 -> 3 -> 2 -> 1
。
思路
本题可以用迭代和递归两种方式求解。
以迭代为例,使用双指针 p r e pre pre、 c u r cur cur。开始时 p r e pre pre 指向空, c u r cur cur 指向头节点 h e a d head head。在反转某个节点时,我们可以临时存储 c u r cur cur 节点的下一个节点,然后把 c u r cur cur 节点的下一个节点更改为 p r e pre pre。接着同时往后移动 p r e pre pre、 c u r cur cur 完成遍历即可。
最终返回 p r e pre pre,即反转后的头节点。
以下代码给了迭代和递归两种实现方式。
代码
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public static void main(String[] args) {
// 待反转链表为 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
// 迭代法反转列表
head = reverseList_1(head);
// 反转后链表应为 5 -> 4 -> 3 -> 2 -> 1
ListNode node = head;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
// 递归法反转列表
head = reverseList_2(head);
// 再次反转后链表应为 1 -> 2 -> 3 -> 4 -> 5
node = head;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
/**
* 迭代反转链表
* @param head 带反转链表的头节点
* @return 反转后链表的头节点
*/
private static ListNode reverseList_1(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
/**
* 递归反转链表
* @param head 带反转链表的头节点
* @return 反转后链表的头节点
*/
private static ListNode reverseList_2(ListNode head) {
if (null == head || null == head.next) return head;
ListNode node = reverseList_2(head.next);
head.next.next = head;
head.next = null;
return node;
}
}