Created
October 22, 2013 13:22
-
-
Save zsh-89/7100677 to your computer and use it in GitHub Desktop.
Leetcode: Copy List with Random Pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list with a random pointer. | |
* struct RandomListNode { | |
* int label; | |
* RandomListNode *next, *random; | |
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {} | |
* }; | |
*/ | |
typedef RandomListNode Node; | |
class Solution { | |
public: | |
void insertShallow(Node * n) { | |
while (n) { | |
Node * p = n; n = n->next; | |
Node * next = p->next; | |
Node * sha = new Node(*p); | |
p->next = sha; | |
sha->next = next; | |
} | |
} | |
void ajustShallow(Node * n) { | |
while (n) { | |
Node * p = n->next; n = n->next->next; | |
if (p->random) p->random = p->random->next; | |
} | |
} | |
Node * pickList(Node * n) { | |
Node * head = n->next; | |
while (n) { | |
Node * p = n; n = n->next->next; | |
Node * copy = p->next; | |
p->next = n; | |
if (n) copy->next = n->next; | |
else copy->next = NULL; | |
} | |
return head; | |
} | |
RandomListNode *copyRandomList(RandomListNode *head) { | |
if (!head) return NULL; | |
insertShallow(head); | |
ajustShallow(head); | |
return pickList(head); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
是的, 就是忘记判断p->random是否为空了
但是这个错误终究还是整个coding的过程不严谨导致的