《剑指offer》复杂链表的复制

题目:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路:

要考虑链表的next和random指针,如果在同一循环里做会比较乱,而且也不好拆分。
所以把复制的步骤分成三个模块,
1、复制next部分。先把所有节点复制一份,加到原有节点后面,形成新的链表。
这里写图片描述
2、复制random部分。在新链表上,把新节点的random指针按照原来的链表一一复制出来。
这里写图片描述
3、拆分原来链表和新添加的链表,将两指针节点相连的部分打断,并返回新的链表。
这里写图片描述
代码是python3的,牛客网是python2.7,正式做题的时候要注意print的区别。

# -*- coding:utf-8 -*-
class RandomListNode:
    def __init__(self, x):
        self.label = x
        self.next = None
        self.random = None
class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        if(pHead==None):
            return None
        pcur=pHead
        while(pcur!=None):
            node=RandomListNode(pcur.label)
            node.next=pcur.next
            pcur.next=node
            pcur=node.next

        pcur = pHead
        while (pcur != None):
            if(pcur.random!=None):
                pcur.next.random = pcur.random.next
            pcur = pcur.next.next
        pcur=pHead
        pnhead=pHead.next
        cur=pnhead
        while(pcur!=None):
            if (pcur.next != None):
                pcur.next=pcur.next.next
            if(cur.next!=None):
                cur.next=cur.next.next
            pcur=pcur.next
            cur = cur.next
        return pnhead

sl=Solution()
node1 = RandomListNode(1)
node2 = RandomListNode(2)
node3 = RandomListNode(3)
node1.next=node2
node2.next=node3
node1.random=node3
node2.random=node1
node3.random=None

nsl=sl.Clone(node1)
while(nsl!=None):
    print(nsl.label)
    if(nsl.random!=None):
        print(nsl.random.label)
    nsl=nsl.next

参考:
https://blog.csdn.net/qq_33431368/article/details/79296360

猜你喜欢

转载自blog.csdn.net/gsch_12/article/details/81452053