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

Copy List with Random Pointer

时间:2016-07-08 10:21:09      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 1 /**
 2  * Definition for singly-linked list with a random pointer.
 3  * class RandomListNode {
 4  *     int label;
 5  *     RandomListNode next, random;
 6  *     RandomListNode(int x) { this.label = x; }
 7  * };
 8  */
 9 public class Solution {
10     public RandomListNode copyRandomList(RandomListNode head) {
11         if (head == null) {
12             return null;
13         }
14         copyNext(head);
15         copyRandom(head);
16         RandomListNode newHead = splitList(head);
17         return newHead;
18     }
19     
20     private void copyNext(RandomListNode head) {
21         while(head != null) {
22             RandomListNode copy = new RandomListNode(head.label);
23             copy.next = head.next;
24             head.next = copy;
25             head = head.next.next;
26         }
27     }
28     
29     private void copyRandom(RandomListNode head) {
30         while (head != null) {
31             if (head.random != null) {
32                 head.next.random = head.random.next;
33             }
34             head = head.next.next;
35         }
36     }
37     
38     private RandomListNode splitList(RandomListNode head) {
39         RandomListNode newHead = head.next;
40         while (head != null) {
41             RandomListNode temp = head.next;
42             head.next = temp.next;
43             head = head.next;
44             if (temp.next != null) {
45                 temp.next = temp.next.next;
46             }
47         }
48         return newHead;
49     }
50 }

 

Copy List with Random Pointer

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5652241.html

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