複雜連結串列的賦值

LingLee_荊棘鳥發表於2017-07-14

連結串列結構中,每個節點不僅有一條指向下一節點的next指標,同時含有一條rand指標,rand指標可能指向任何一個連結串列中的節點,請複製這種含有rand指標節點的連結串列。

 

方法1.建立一個沒有rand時與複雜連結串列完全相同的連結串列,然後遍歷原連結串列,給新連結串列rand複製。


方法2.



public class Solution {
	public RandomListNode Clone(RandomListNode head) {
		if (head == null) {
			return null;
		}
		RandomListNode cur = head;
		RandomListNode next = null;
		// copy node and link to every node
		while (cur != null) {
			next = cur.next;
			cur.next = new RandomListNode(cur.label);
			cur.next.next = next;
			cur = next;
		}
		cur = head;
		RandomListNode curCopy = null;
		// set copy node rand
		while (cur != null) {
			next = cur.next.next;
			curCopy = cur.next;
			curCopy.random = cur.random != null ? cur.random.next : null;
			cur = next;
		}
		RandomListNode res = head.next;
		cur = head;
		// split
		while (cur != null) {
			next = cur.next.next;
			curCopy = cur.next;
			cur.next = next;
			curCopy.next = next != null ? next.next : null;
			cur = next;
		}
		return res;
	}
}


相關文章