题目链接:
题目描述:
#206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
通过次数295,766 提交次数422,186
方法一:迭代法
对于每个节点,需要做以下三步:
- 保存当前节点的下一个节点
next
; - 让当前节点
cur
指向前一个节点pre
; - 删除
pre -> cur
这条链,否则链表中会形成环。
代码:
/**
* 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) return null;
ListNode pre = null, cur = head, next = head;
while(cur.next != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
cur.next = pre;
return cur;
}
}
提交截图:
第一次提交的内存消耗:
空间优化:
从代码中可以看出,没必要设置 cur 指针,用 head 即可。改变化可以让直行内存消耗从“击败了73.32%的 java 提交记录” 变成 “击败了 94.97%的 java 提交记录”。
/**
* 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) return null;
ListNode pre = null, next = head;
while(head.next != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
head.next = pre;
return head;
}
}
第二次提交的内存消耗:
方法二:递归法
递归法解决该问题需要以下几步:
- 首先,要一层一层往下,找到链表的最后一个节点,也就是我们最后要返回的节点;
- 然后,将当前节点的下下个节点指向当前节点,注意不要动第一步我们找到的要返回的节点;
- 最后,同样是为了避免链表中形成环,需要删掉当前节点和下一个节点之间的链路。
代码:
/**
* 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 res = reverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}
提交截图: