【leetcode】206.反转链表

简介: 【leetcode】206.反转链表

17.png


解法一

在遍历链表时,定义一个链表的前驱结点 prev ,然后一边遍历一边把 cur(此节点)的 next 指向 prev ,直到链表遍历完。


需要注意的是,cur 的 next 指向 prev 之后就不能达到从前往后遍历的效果了,所以我们需要提前记录 cur 的 next ,并且 prev 应随着 cur 一起往后走,并且一直是 cur 的前驱结点


public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode prev = null;     // 定义前驱结点
        while (cur != null) {
            ListNode next = cur.next;    // 提前记录 cur.next
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

解法二

使用递归思路完成

可以把整条链表看成是 head(头结点)+ 剩余节点,就可以先将剩余结点反转,再将头结点尾插到最后。


public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode secondNode = head.next;    // 现在的第二个节点,就是反转后的最后一个节点
        ListNode reverseHead = reverseList(secondNode);     // 反转后的头结点
        head.next = null;
        secondNode.next = head;
        return reverseHead;
    }
目录
相关文章
|
6天前
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
6天前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
6天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
6天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II