复杂链表的复制笔记

剑指offer 复杂链表复制

描述

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

大概思路

复制链表成A->A'->B->B'->C->C'.....
**注意:需要复制next和random2个指针**
拆分,return head节点即可。
/*
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 p = pHead;

        while(p!=null){//复制next指针
            RandomListNode node = new RandomListNode(p.label);
            node.next=p.next;
            p.next=node;
            p=node.next;
        }
        p=pHead;//p继续指向头结点,开始复制random指针
        while(p!=null){
            if(p.random!=null)
                p.next.random = p.random.next;
            p = p.next.next;

        }
        RandomListNode head = pHead.next;
        RandomListNode cur = head; // 初始化head和cur都指向A',head用于返回。cur记录拆分过程的当前节点
        p = pHead;
        while(p!=null){
            p.next=p.next.next;
            if(cur.next!=null){
                cur.next = cur.next.next;
            }
            p=p.next;
            cur=cur.next;

        }
        return head;


    }
}

猜你喜欢

转载自blog.csdn.net/xuezhan123/article/details/79618465
今日推荐