1. 程式人生 > >leetcode--138. Copy List with Random Pointer

leetcode--138. Copy List with Random Pointer

問題 pan copy clas leet cnblogs node title lin

1,問題描述

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.

數據結構:

1 /**
2  * Definition for singly-linked list with a random pointer.
3  * class RandomListNode {
4  *     int label;
5  *     RandomListNode next, random;
6 * RandomListNode(int x) { this.label = x; } 7 * }; 8 */

2,邊界條件:root==null情況可以處理,所以沒有邊界條件,不需要特殊處理

3,解題思路:先不管random指針,把鏈表節點依次復制,不過不是生成一個新的鏈表,而是把新節點放在原節點的next。然後再根據random指針把新節點的random指針指向原節點的next,即新節點。最後把大鏈表分離,恢復舊鏈表,把新節點生成一個新鏈表,即為舊鏈表的deep copy。

4,代碼實現

 1 public RandomListNode copyRandomList(RandomListNode head) {
2 if (head == null) { 3 return null; 4 } 5 RandomListNode cur = head; 6 while (cur != null) { 7 RandomListNode node = new RandomListNode(cur.label); 8 node.next = cur.next; 9 cur.next = node; 10 cur = node.next; 11 } 12 13 cur = head;
14 while (cur != null && cur.next != null) { 15 if (cur.random != null) { 16 cur.next.random = cur.random.next; 17 } 18 cur = cur.next.next; 19 } 20 21 RandomListNode dummy = new RandomListNode(-1); 22 // RandomListNode copyCur = head.next;//這種寫法在leetcode不通過,在lintcode上面能通過 23 // dummy.next = copyCur; 24 // cur = head.next.next; 25 RandomListNode copyCur = dummy;//這裏是註意下,比上面寫法簡潔,可以處理head=null的情況 26 cur = head; 27 while (cur != null && cur.next != null) { 28 copyCur.next = cur.next; 29 cur.next = cur.next.next; 30 cur = cur.next; 31 copyCur = copyCur.next; 32 } 33 return dummy.next; 34 }

5,時間復雜度:O(n),空間復雜度:O(1)

6,api:無

leetcode--138. Copy List with Random Pointer