20180722剑指offer题26——复杂链表的复制

一、要求

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。值得注意的是,像节点D的randomnext就是None,不是所有节点都有randomnext的非空节点

二、思路及代码

三步走

step1:在原节点后插入新建节点,注意不能用=来新建节点

step2:对新节点完善randomnext属性

step3:根据跳一跳,拆分成两个链表

class RandomListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        self.randomnext = None

def solution(headnode):
    if not headnode:
        return
    CloneNodes(headnode)
    ConnectRandomNext(headnode)
    return SplitNodes(headnode)#一定要return新链表的头结点

def CloneNodes(headnode):
    pnode=headnode
    while pnode:
        qnode=RandomListNode(pnode.val)
        qnode.next=pnode.next
        pnode.next=qnode
        pnode=qnode.next

def ConnectRandomNext(headnode):
    pnode=headnode
    while pnode:
        qnode = pnode.next
        if pnode.randomnext:
            qnode.randomnext=pnode.randomnext.next
        pnode=qnode.next

def SplitNodes(headnode):
    pnode=headnode
    qnode=cloneheadnode=headnode.next
    while pnode:
        pnode.next=qnode.next
        if qnode.next:
            qnode.next=qnode.next.next#注意最后一个节点
        pnode=pnode.next
        qnode=qnode.next
    return cloneheadnode

node1 = RandomListNode(1)
node2 = RandomListNode(3)
node3 = RandomListNode(5)
node1.next = node2
node2.next = node3
node1.randomnext = node3

newnode=solution(node1)
print(newnode.val,newnode.next.val,newnode.randomnext.val)

三、运行结果

1 3 5

四、思考与总结

1.这个题目知道套路三步走后好像难度还行?就是不断在拆建链接

2.pq大法好

猜你喜欢

转载自blog.csdn.net/weixin_41819299/article/details/81155676
今日推荐