複雜鏈表的複製——Java

輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的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 pCur = pHead;
        while (pCur!=null){
            RandomListNode listNode = new RandomListNode(pCur.label);
            listNode.next = pCur.next;
            listNode.random = null;
            pCur.next = listNode;
            pCur = listNode.next;
        }
        //給random賦值
        pCur=pHead;
        while (pCur!=null){
            if(pCur.random!=null)
                pCur.next.random = pCur.random.next;
            pCur=pCur.next.next;
        }
        //分離clone的鏈表,並還原原鏈表
        pCur =pHead.next;
        RandomListNode head = pHead.next;
        RandomListNode cur = head;
        pCur = pHead;
        while (pCur!=null){
            pCur.next = pCur.next.next;
            if(cur.next!=null)
                cur.next=cur.next.next;
            cur=cur.next;
            pCur = pCur.next;
        }
        return head;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章