• 复杂链表的复制


     题目描述

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

    方法一:

    /*

    *解题思路:
    *1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
    *2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
    *3、拆分链表,将链表拆分为原链表和复制后的链表
    */

    class Solution:
        # 返回 RandomListNode
        def Clone(self, pHead):
            # write code here
            if not pHead:
                return None
            #复制节点
            p1=pHead
            while p1:
                node=RandomListNode(p1.label)
                pnext=p1.next
                p1.next=node
                node.next=pnext
                p1=pnext
            #复制节点的random
            p2=pHead
            while p2:
                if p2.random:
                    p2.next.random=p2.random.next
                p2 = p2.next.next
            #拆分链表(原链表的节点拆掉不要)
            cop = pHead.next
            cur = pHead
            nxt = pHead.next
            while nxt:
                cur.next = nxt.next
                cur = nxt
                nxt.next=cur.next
                nxt = cur.next
            return cop

    方法二:

    递归实现

    class Solution:
        def Clone(self, head):
            if not head: return
            newNode = RandomListNode(head.label)
            newNode.random = head.random
            newNode.next = self.Clone(head.next)
            return newNode
  • 相关阅读:
    go学习中的零散笔记
    git reset --hard与git reset --soft的区别
    php必学必会
    gdb 解core
    php学习
    高仿京东到家APP引导页炫酷动画效果
    RxHttp
    SVN回滚文件
    遍历枚举
    python3 多线程
  • 原文地址:https://www.cnblogs.com/girl1314/p/10469293.html
Copyright © 2020-2023  润新知