原题链接: https://leetcode.com/problems/reverse-linked-list/
1. 题目介绍
Reverse a singly linked list.
反转一个单向链表。
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
通过迭代或者递归递都可以反转一个链表,你能实现这两个方法吗?
2. 解题思路
2.1 使用堆栈
利用堆栈的先入后出的特性实现链表的反转。这是我首先想到的方法。
实现代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
Stack<Integer> s = new Stack<Integer>();
ListNode cur = head;
while(cur != null){
s.push(cur.val);
cur = cur.next;
}
ListNode ans = new ListNode(0);
cur = ans;
while(!s.empty()){
cur.next = new ListNode(s.pop());
cur = cur.next;
}
return ans.next;
}
}
2.2 当前节点指向前一个元素
在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
注:此方法来自:https://leetcode-cn.com/problems/reverse-linked-list/solution/
实现代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode cur = head;
ListNode before = null;
while(cur != null){
ListNode behind = cur.next;
cur.next = before;
before = cur;
cur = behind;
}
return before;
}
}
2.3 递归
递归版本稍微复杂一些,其关键在于反向工作。假设列表的其余部分已经被反转,现在我该如何反转它前面的部分?
假设列表为:n1 → … → nk-1 → nk → nk+1 → … → nm → Ø
若从节点 nk+1 到 nm 已经被反转,而我们正处于 nk。
现在的情况如下:
n1 → … → nk-1 → nk → nk+1 ← … ← nm
我们希望 nk+1 的下一个节点指向 nk。
所以,nk.next.next = nk;
要小心的是 n1 的下一个必须指向 Ø 。如果你忽略了这一点,你的链表中可能会产生循环。
注:此方法来自:https://leetcode-cn.com/problems/reverse-linked-list/solution/
实现代码
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode before = reverseList(head.next);
head.next.next = head;
head.next = null;
return before;
}
}
3. 参考资料
https://leetcode-cn.com/problems/reverse-linked-list/solution/
https://leetcode.com/problems/reverse-linked-list/solution/