您的位置:首页 > 运维架构

LeetCode — Copy List with Random Pointer 解题报告

2013-12-26 10:06 561 查看
转载请注明: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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息