劍指offer(二十五)——複雜鏈表的複製

劍指offer(二十五)——複雜鏈表的複製

題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)

題解
(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)這句話很重要,雖然我不知道它是怎麼實現的。一開始我並不知道怎麼做,只能膜拜大佬,知道這種題的經典做法。處處坑啊!

  • 直接搬下來了,說的非常清楚,分三步走就可以了。
  • 唯一納悶的是,爲什麼兩條鏈得都拆開啊,只拆一條不行嗎?
    在這裏插入圖片描述
	public RandomListNode Clone(RandomListNode pHead)
    {
		if (pHead == null) {
			return pHead;
		}
		//第一步
		RandomListNode tempNode = pHead;
		while(tempNode != null) {
			RandomListNode t = new RandomListNode(tempNode.label);
			RandomListNode nextt = tempNode.next;
			tempNode.next = t;
			t.next = nextt;
			tempNode = nextt;
		}
		//第二步
		tempNode = pHead;
		while(tempNode != null) {
			
			if (tempNode.random != null) {
				tempNode.next.random = tempNode.random.next;
			}
			tempNode = tempNode.next.next;
		}
		//第三步
		tempNode = pHead;
		RandomListNode resultList = pHead.next;
		while(tempNode != null){
			RandomListNode t = tempNode.next;
			tempNode.next = t.next;
			if (t.next != null) {
				t.next = t.next.next;
			}
			tempNode = tempNode.next;
		}
		return resultList;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章