【链表】LeetCode #反转链表(两种方法:迭代法、递归法)

题目链接:

LeetCode #反转链表

题目描述:

#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;
    }
}

提交截图:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值