2014.1.13 20:45
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.
Solution:
First of all, the problem description indicated that you have to return a deep copy of the linked list.
Here are the wikis for deep copy and shallow copy for your information.
My solution is to mark each list node with a number, which makes them easy to be numbered and identified.
Marking the nodes with numbers and recording the pointings between these numbers are like object serialization, while recontrcuting another identical list using these marked numbers is exactly the deserialization process.
Pointers are not persistent data, that's why you have to serialize them before making a deep copy. If you don't, you get a shallow copy instead.
Time complexity is O(n * log(n)), as stl <map> requires O(log(n)) time for each search and insert operation. Space complexity is O(n) using stl <map>.
If you replace stl <map> with <unordered_map>, you'll theoretically achieve O(n) time, but actually you get tiny improvement in performance. As <map> is not that slow and <unordered_map> not that fast too. Space usages are on the same level.
Accepted code:
1 // 1CE, 1RE, 2WA, 1AC, not easy~ 2 #include <map> 3 using namespace std; 4 /** 5 * Definition for singly-linked list with a random pointer. 6 * struct RandomListNode { 7 * int label; 8 * RandomListNode *next, *random; 9 * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 RandomListNode *copyRandomList(RandomListNode *head) { 15 // IMPORTANT: Please reset any member data you declared, as 16 // the same Solution instance will be reused for each test case. 17 int n; 18 19 if(nullptr == head){ 20 return nullptr; 21 } 22 23 n = 0; 24 RandomListNode *ptr; 25 26 mri.clear(); 27 mir.clear(); 28 29 ptr = head; 30 while(ptr != nullptr){ 31 ++n; 32 mri[ptr] = n; 33 ptr = ptr->next; 34 } 35 36 RandomListNode *root = new RandomListNode(0), *tail; 37 ptr = head; 38 // 1CE here, undefined $i 39 int i = 0; 40 tail = root; 41 while(ptr != nullptr){ 42 ++i; 43 tail->next = new RandomListNode(ptr->label); 44 tail = tail->next; 45 mir[i] = tail; 46 ptr = ptr->next; 47 } 48 49 RandomListNode *p1, *p2; 50 51 p1 = head; 52 p2 = root->next; 53 while(p1 != nullptr){ 54 // 1RE here, mapping using nullptr doesn't work 55 if(p1->random != nullptr){ 56 p2->random = mir[mri[p1->random]]; 57 } 58 p1 = p1->next; 59 // 2WA here, forgot to move $p2 forward 60 p2 = p2->next; 61 } 62 63 head = root->next; 64 delete root; 65 mir.clear(); 66 mri.clear(); 67 68 return head; 69 } 70 private: 71 map<RandomListNode *, int> mri; 72 map<int, RandomListNode *> mir; 73 };