链表相关编程题总结

1、复制带随机指针的链表

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head is None:
            return None
        p = head
        while p:
            node = Node(x=p.val, next=p.next)
            p.next = node
            p = p.next.next
        p = head
        while p:
            if p.random:
                p.next.random = p.random.next
            else:
                p.next.random = None
            p = p.next.next
        p = head.next
        head = p
        while p.next:
            p.next = p.next.next
            p = p.next
        return head

猜你喜欢

转载自www.cnblogs.com/weswes/p/12078923.html
今日推荐