LeetCode: Copy List with Random Pointer題解

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.


public RandomListNode copyRandomList(RandomListNode head) {
		if (head == null)
			return null;
		RandomListNode nhead = new RandomListNode(head.label);
		RandomListNode optr = head;
		RandomListNode nptr = nhead;
		Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
		map.put(optr, nptr);
		nptr.random = optr.random;

		optr = optr.next;
		while (optr != null) {
			RandomListNode tmp = new RandomListNode(optr.label);
			nptr.next = tmp;
			nptr = tmp;
			nptr.random = optr.random;
			map.put(optr, nptr);
			optr = optr.next;
		}
		nptr.next = null;
		nptr = nhead;
		while (nptr != null) {
			if (nptr.random != null) {
				nptr.random = map.get(nptr.random);
			}
			nptr = nptr.next;
		}

		return nhead;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章