Skip to content

Instantly share code, notes, and snippets.

@zsh-89
Created October 22, 2013 13:22
Show Gist options
  • Save zsh-89/7100677 to your computer and use it in GitHub Desktop.
Save zsh-89/7100677 to your computer and use it in GitHub Desktop.
Leetcode: Copy List with Random Pointer
/**
* 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);
}
};
@zsh-89
Copy link
Author

zsh-89 commented Oct 22, 2013

Runtime error了一次才AC的
太不上心了,教训值得铭记!
写完一定要做Check
每一个"->"前面的东西你一定要保证它非空

p->random = p->random->next;
这句我忘记加guard了

@eclipselu
Copy link

if (p->random) p->random = p->random->next;

之前是这里没有加判断所以 Runtime Error 了吗?

@eclipselu
Copy link

其它 :lgtm:

@zsh-89
Copy link
Author

zsh-89 commented Oct 22, 2013

是的, 就是忘记判断p->random是否为空了

但是这个错误终究还是整个coding的过程不严谨导致的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment