码迷,mamicode.com
首页 > 其他好文 > 详细

25、复杂链表的复制

时间:2017-08-30 11:55:14      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:dom   solution   turn   链表   节点   结果   span   log   rand   

一、题目

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

二、解法

 1 public class Solution {
 2     //递归
 3     /*public RandomListNode Clone(RandomListNode pHead)
 4     {
 5         if(pHead == null) return null;
 6             RandomListNode newHead = new RandomListNode(pHead.label);
 7             newHead.random = pHead.random;
 8             newHead.next = Clone(pHead.next);
 9             return newHead;
10     }*/
11     
12     public RandomListNode Clone(RandomListNode pHead){
13          if(pHead == null)
14              return null;
15          RandomListNode pCur = pHead;
16          //1、复制原结点的next,如原来是A->B->C 变为 A->A‘->B->B‘->C->C‘
17          while(pCur != null){
18              RandomListNode node = new RandomListNode(pCur.label);
19              node.next = pCur.next;//将node的next指向pCUr的next  A‘->B  A->B
20              pCur.next = node;//将pCur.next指向node A->A‘->B
21              pCur = node.next;//将pCur指向node.next 下次辅助B
22          }
23          pCur = pHead;//将pCur指向pHead
24          //2、复制random指针,  pCur是原来链表的结点,pCur.next是复制pCur的结点
25          while(pCur != null){
26              if(pCur.random != null)//如果pCur.random不为空
27                 //将pCur的random指针的next就是pCur.next的random指针指向的结点
28                  pCur.next.random = pCur.random.next;
29              pCur = pCur.next.next;//移动pCur指针
30          }
31          //新建一个head结点,指向pHead的next结点,即指向拆分链表的头结点
32          RandomListNode head = pHead.next;
33          //新建一个cur结点,指向拆分链表的head头结点
34          RandomListNode cur = head;
35          //将pCur指向头结点
36          pCur = pHead;
37          //3、拆分链表
38          while(pCur != null){
39              pCur.next = pCur.next.next;
40              if(cur.next != null)//cur.next有可能为空,当最后一个结点的时候
41                  cur.next = cur.next.next;
42              cur = cur.next;//后移指针
43              pCur = pCur.next;//后移指针
44          }
45          return head;
46      }
47 }

 

25、复杂链表的复制

标签:dom   solution   turn   链表   节点   结果   span   log   rand   

原文地址:http://www.cnblogs.com/fankongkong/p/7452114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!