[LeetCode] 206. Reverse Linked List

原题链接: 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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值