转载请注明:http://blog.csdn.net/ict2014/article/details/17577191
原题如下:
题目解析:
这道题目是“复杂链表的复制”。很经典的一道题目,可以从网上进行搜索,比如可以参考这篇文章:复杂链表复制。
我们按照传统的做法进行解题。总共分为三步:
1、申请结点并且连接成一个链表
2、random pointer的赋值
3、拆分链表成两个链表
题目代码:
/**
* 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) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode* new_head = NULL;
if(head == NULL){
return new_head;
}
//copy and connect
CopyAndConnect(new_head, head);
//set the random
SetRandom(head);
//split into two list
SplitToTwoLists(head);
return new_head;
}
//copy the list to new list
//connect the two lists
void CopyAndConnect(RandomListNode* &new_head,
RandomListNode* head){
bool first = true;
RandomListNode* next, *new_node;
while(head != NULL){
next = head->next;
new_node = new RandomListNode(head->label);
new_node->next = next;
head->next = new_node;
if(first){
new_head = new_node;
first = false;
}
head = next;
}
}
//set the random
void SetRandom(RandomListNode* head){
while(head != NULL){
if(head->random != NULL){
head->next->random = head->random->next;
}
head = head->next->next;
}
}
//split into two list
void SplitToTwoLists(RandomListNode* head){
RandomListNode* next;
while(head != NULL){
next = head->next;
head->next = next->next;
if(next->next == NULL){
next->next = NULL;
}else{
next->next = next->next->next;
}
head = head->next;
}
}
};