Shirlies
宁静专注认真的程序媛~

题目:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

链接:

http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:

剑指offer上面给出的题解,只想说,太厉害了!

1、遍历当前链表,将遍历的节点复制一份,插入到当前节点的后面

2、遍历新的链表,根据当前节点的random指针修改后面的复制节点的random指针

3、拆分新的链表即可。

代码:

 1 /*
 2 struct RandomListNode {
 3     int label;
 4     struct RandomListNode *next, *random;
 5     RandomListNode(int x) :
 6             label(x), next(NULL), random(NULL) {
 7     }
 8 };
 9 */
10 class Solution {
11 public:
12     RandomListNode* Clone(RandomListNode* pHead)
13     {
14         if(pHead == NULL){
15             return NULL;
16         }
17         
18         RandomListNode *pIter = pHead;
19         while(pIter != NULL){
20             RandomListNode *newNode = new RandomListNode(pIter->label);
21             //将newNode插入到pIter之后
22             newNode->next = pIter->next;
23             pIter->next = newNode;
24             pIter = newNode->next;
25         }
26         
27         //修改随机节点
28         pIter = pHead;
29         while(pIter != NULL){
30             RandomListNode *copyNode = pIter->next;
31             if(pIter->random != NULL){
32                 copyNode->random = pIter->random->next;
33             }
34             pIter = copyNode->next;
35         }
36         
37         //拆分链表
38         RandomListNode *pAnsHead = pHead->next;
39         RandomListNode *pAnsIter = pAnsHead;
40         pIter = pHead;
41         while(pIter != NULL){
42             pIter->next = pAnsIter->next;
43             if(pAnsIter->next != NULL){
44                 pAnsIter->next = pAnsIter->next->next;
45             }
46 
47             pIter = pIter->next;
48             pAnsIter = pAnsIter->next;
49         }
50         
51         return pAnsHead;
52     }
53 };

 

posted on 2016-09-03 10:21  Shirlies  阅读(203)  评论(0)    收藏  举报