首页 > 其他 > 详细

翻转链表

时间:2021-06-26 16:56:56      阅读:25      评论:0      收藏:0      [点我收藏+]

描述

输入一个链表,反转链表后,输出新链表的表头。

算法

  1. 因为链表结尾是 null,所以让 pre 的值是 null, p 就表示我们的头部
    技术分享图片

  2. 因为 p 的 next 成员马上就要指向 pre, 如果不保存 p 的下一个节点就会使其丢失,所以通过临时变量 t 保存它
    技术分享图片

  3. 让 P 的 next 成员指向 pre
    技术分享图片

  4. pre 移动到 p 的位置,p 移动到 t 的位置,此时我们就回到了第一步中的情况
    技术分享图片

  5. 保持这个循环不变式直到 p 移动到原链表结尾我们就获得了翻转之后的链表。

// c++
class Solution {
public:
    ListNode* ReverseList(ListNode* p) {
        ListNode* pre = nullptr;
        while (p) {
            ListNode* t = p->next;
            p->next = pre;
            pre = p;
            p = t;
        }
        return pre;
    }
};
# python3
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        pre = None
        cur = pHead
        while cur:
            tmp = cur.next
            cur.next = pre 
            pre = cur 
            cur = tmp 
        return pre

遍历一次链表,时间复杂度是 O(n),空间复杂度是 O(1)。

另一种解法

如果上面的方法不便于理解,我们可以用数组把链表的每个元素都保存下来,翻转之后再重建链表,不过不推荐这种做法,它的时间复杂度是 O(n), 空间复杂度是 O(n)。

// c++
class Solution {
public:
    ListNode* ReverseList(ListNode* p) {
        if (!p) return p;
        vector<ListNode*> res;
        for (; p; p = p->next) {
            res.emplace_back(p);
        }
        reverse(res.begin(), res.end());
        for (int i = 0; i < res.size() - 1; i++) {
            res[i]->next = res[i + 1];
        }
        res[res.size() - 1]->next = nullptr;
        return res[0];
    }
};
# python3
class Solution:
    # 返回ListNode
    def ReverseList(self, p):
        # write code here
        if not p: return p 
        res = []
        while p:
            res.append(p)
            p = p.next
        res = list(reversed(res))
        for i in range(len(res) - 1):
            res[i].next = res[i + 1]
        res[-1].next = None
        return res[0]

翻转链表

原文:https://www.cnblogs.com/byteMemory/p/14933822.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!