剑指Offer:复杂链表的复制Java/Python

1.题目描述

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

2. 算法描述

1.如果链表为空,直接返回空。
2.如果链表不为空,分两步走:
a) \red{复制} :顺序复制每个结点得到新结点,将得到的新结点作为被复制结点的后继(新结点的随机指针暂时未空);然后重新遍历一遍链表,将所有新结点的随机指针复制
b) \red{拆分} :再次遍历一遍链表,将源链表和新结点的所有后继指针更改便完成拆分。

示例:(没有画出的箭头均为空指针)

复制每个结点得到新结点, 将得到的新结点作为被复制结点的后继(新结点的随机指针暂时为空)

将得到的新结点作为被复制结点的后继(新结点的随机指针暂时为空)

所有新结点的随机指针复制

所有新结点的随机指针复制

拆分:源链表的所有后继指针更改

拆分

3.代码描述

3.1.Java代码

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;
    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead){
        if(pHead==null) return null;
        RandomListNode old = pHead, temp = null;
        //复制链表结点
        while(old!=null){
            temp = new RandomListNode(old.label);
            temp.next = old.next;
            old.next = temp;
            old = old.next.next;
        }
        //复制链表随机指针 和 修改后继指针
        old = pHead;
        while(old!=null){
            if(old.random!=null)
                old.next.random = old.random.next;
            old = old.next.next;
        }
        //拆分
        RandomListNode newHead = pHead.next;
        old = pHead;
        temp = newHead;
        while(temp.next!=null){
            old.next = temp.next;
            old = temp.next;
            temp.next = old.next;
            temp = old.next;
        }
        old.next = null;//不要忘记置空
        return newHead;
    }
}

3.2.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 pHead==None:
            return None
        old = pHead
        temp = None
        while old:
            temp = RandomListNode(old.label)
            temp.next = old.next
            old.next = temp
            old = old.next.next
        
        old = pHead
        while old:
            if old.random:
                old.next.random = old.random.next
            old = old.next.next
        
        newHead = pHead.next
        old = pHead
        temp = newHead
        while temp.next:
            old.next = temp.next
            old = temp.next
            temp.next = old.next
            temp = old.next
        old.next = None
        return newHead

猜你喜欢

转载自blog.csdn.net/qq_37888254/article/details/89737256
今日推荐