剑指offer-复杂链表的复制(python)

在这里插入图片描述

# -*- 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):
        # write code here
        """
        if not pHead:
            return None
        newnode=RandomListNode(pHead.label)
        newnode.random=pHead.random
        newnode.next=self.Clone(pHead.next)
        return newnode
        """
        if not pHead:
            return None
        cur=pHead
        #在原链表中插入一个与前面元素相同的node
        """
        1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
        2、遍历链表,A1->random = A->random->next;
        3、将链表拆分成原链表和复制后的链表
        """
        while cur:
            tmp = RandomListNode(cur.label)
            tmp.next = cur.next
            cur.next = tmp
            cur = tmp.next
        cur  = pHead
        while cur:
            tmp=cur.next
            if cur.random:
                tmp.random=cur.random.next
            cur=tmp.next
        cur=pHead
        res=pHead.next
        while cur.next:
            tmp=cur.next
            cur.next=tmp.next
            cur=tmp
        return res
发布了69 篇原创文章 · 获赞 46 · 访问量 5264

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104268791
今日推荐