剑指 Offer 06. 从尾到头打印链表 24. 反转链表 35. 复杂链表的复制 Python 3

从尾到头打印链表 

单向链表:数据+指针(存储地址),只可根据next指针遍历查找,查询慢,插入和删除快,不知道前驱节点时删除和插入的时间复杂度都为O(n),若给定前驱节点则时间复杂度为O(1)。

思路:递归链表,将所有值存入list,倒序输出

时间复杂度O(n)

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        # 存入列表,倒序输出
        printlist = list()
        cur = head
        while cur:
            printlist.append(cur.val)
            cur = cur.next
        return printlist[::-1]

反转链表

思路:递归时记录当前节点的下一个节点,并将当前节点的next指针指向前一个节点

时间复杂度O(n)

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur = head
        pre = None
        while cur:
            curnext = cur.next
            cur.next = pre
            pre = cur
            cur = curnext
        return pre

递归思想版:

条件:问题可拆解,拆解问题解决方式相同,存在最小子问题

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
            
        cur = self.reverseList(head.next)
        head.next.next = head
        head.next = None

        return cur

复杂链表的复制

难点:random指针的赋值

思路:先在原节点后复制一个相同的节点后将复制的节点拆分,random先与原来节点指向相同,后再指向复制的节点

剑指 Offer 06. 从尾到头打印链表 24. 反转链表 35. 复杂链表的复制 Python 3_第1张图片

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return 

        cur = head
        while cur:
            curnext = cur.next
            currandom = cur.random
            copycur = Node(cur.val)
            copycur.next = curnext
            copycur.random = currandom
            cur.next = copycur
            cur = curnext
            
        cur = head.next
        while cur:
            print(cur.val)
            if cur.random:
                cur.random = cur.random.next
            else:
                cur.random = None
            if cur.next:
                cur = cur.next.next
            else:
                break

        cur = head.next
        copyhead = cur
        while cur.next:
            cur.next = cur.next.next 
            cur = cur.next

        return copyhead

 方法2:   哈希表

思路:原链表作为key,copy链表作为value

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return 
        # 使用字典
        copydic = dict()
        cur = head
        while cur:
            copydic[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            copydic[cur].next = copydic.get(cur.next) # cur.next键的值
            copydic[cur].random = copydic.get(cur.random)
            cur = cur.next
        return copydic[head]

 

你可能感兴趣的:(剑指Offer,链表,python,数据结构)