从收到批准短信到拿到卡总共5天半时间,还包括一个周末# EB23 - 劳工卡
g*j
1 楼
经典题目,就是一个linked list,每个节点有一个指针指向random的节点,然后呢,
copy这个list,
基本思路就是在每个节点后面插入一个同样的节点,然后设置好random的指针,最后把
这个list exact出来
举例: 1->2->3->4 其中 1->3 2->4
变成 1->1'->2->2'->3->3'->4->4' 其中 1'->3' 2'->4'
始终有runtime error, 被搞死了,谢了!
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused
by each test case.
RandomListNode * p = head;
if(p == NULL) return NULL;
while(p != NULL) {
RandomListNode * newNode = new RandomListNode(p->label);
newNode->next = p->next;
p->next = newNode;
p = p->next->next;
}
p = head;
while(p != NULL) {
if(p->random != NULL)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
RandomListNode * newHead = p->next;
RandomListNode * q = newHead;
while(p != NULL) {
p->next = q->next;
q->next = p->next->next;
q = q->next;
p = p->next;
}
return newHead;
}
};
copy这个list,
基本思路就是在每个节点后面插入一个同样的节点,然后设置好random的指针,最后把
这个list exact出来
举例: 1->2->3->4 其中 1->3 2->4
变成 1->1'->2->2'->3->3'->4->4' 其中 1'->3' 2'->4'
始终有runtime error, 被搞死了,谢了!
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused
by each test case.
RandomListNode * p = head;
if(p == NULL) return NULL;
while(p != NULL) {
RandomListNode * newNode = new RandomListNode(p->label);
newNode->next = p->next;
p->next = newNode;
p = p->next->next;
}
p = head;
while(p != NULL) {
if(p->random != NULL)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
RandomListNode * newHead = p->next;
RandomListNode * q = newHead;
while(p != NULL) {
p->next = q->next;
q->next = p->next->next;
q = q->next;
p = p->next;
}
return newHead;
}
};