反转链表-leetcode
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000] -5000 <= Node.val <= 5000
解法一
思路:
迭代置换,p,q,r三个指针,转换q.next=p,之后p=q,q=r,r=r.next。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p,q,r;
p = head;q=head.next;r=head.next.next;
while(true){
if(p==head)p.next=null;
q.next=p;
p=q;
q=r;
if(q==null) break;
r=r.next;
}
return p;
}
}
解法二
思路:
来自官方解答。
递归版本稍微复杂一些,其关键在于反向工作。假设链表的其余部分已经被反转,现在应该反转它前面的部分。设链表为:

若从节点
到
已经被反转,而我们正处于
。

我们希望
的下一个节点指向 
所以,
需要注意的是
的下一个节点必须指向 ∅。如果忽略了这一点,链表中可能会产生环
代码:
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;
}
}

浙公网安备 33010602011771号