@@ -15,33 +15,31 @@ public class CloneWithRandPointers<E extends Comparable<E>> extends DoubleLinked
15
15
public static <E extends Comparable <E >> DoubleLinkedList <E > clone (DoubleLinkedNode <E > node ) {
16
16
DoubleLinkedNode <E > curr = node ;
17
17
18
- // copy node and insert after it
19
- while (curr != null && curr . next != null ) {
18
+ // copy each node and insert after it
19
+ while (curr != null ) {
20
20
DoubleLinkedNode <E > newNode = new DoubleLinkedNode <>(null , curr .item , curr .next );
21
21
curr .next = newNode ;
22
22
curr = curr .next .next ;
23
23
}
24
24
25
+ // copy all random pointers from original node to the copied node
25
26
curr = node ;
26
-
27
- // copy all random pointers
28
27
while (curr != null && curr .next != null ) {
29
- curr .next .prev = curr .prev ;
28
+ curr .next .prev = ( curr .prev != null ) ? curr . prev . next : null ;
30
29
curr = curr .next .next ;
31
30
}
32
31
32
+ // separate the copied nodes into a different linked list
33
33
curr = node ;
34
34
DoubleLinkedNode <E > cloneHead = node .next ;
35
- DoubleLinkedNode <E > dupNode ;
36
- // separate the copy nodes into a different linked list
37
- while (curr != null ) {
35
+ DoubleLinkedNode <E > dupNode = cloneHead ;
36
+ while (curr != null && curr .next != null ) {
38
37
dupNode = curr .next ;
39
38
curr .next = (dupNode != null ) ? dupNode .next : null ;
40
- if (dupNode != null ) {
41
- dupNode .next = (curr .next != null ) ? curr .next .next : null ;
42
- }
39
+ dupNode .next = (curr .next != null ) ? curr .next .next : null ;
43
40
curr = curr .next ;
44
41
}
42
+
45
43
return DoubleLinkedList .getLinkedList (cloneHead );
46
44
}
47
45
@@ -51,13 +49,14 @@ public static void main(String a[]) {
51
49
linkedList .add (11 );
52
50
linkedList .add (22 );
53
51
linkedList .add (33 );
54
- linkedList .getNode (0 ).prev = linkedList . getNode ( 2 ) ;
55
- linkedList .getNode (1 ).prev = linkedList .getNode (3 );
52
+ linkedList .getNode (0 ).prev = null ;
53
+ linkedList .getNode (1 ).prev = linkedList .getNode (2 );
56
54
linkedList .getNode (2 ).prev = linkedList .getNode (0 );
57
55
linkedList .getNode (3 ).prev = linkedList .getNode (1 );
58
56
linkedList .printList ();
59
57
DoubleLinkedList <Integer > clonedList = clone (linkedList .getNode (0 ));
60
58
clonedList .size = 4 ;
59
+ clonedList .set (0 , 234 );
61
60
clonedList .set (1 , 567 );
62
61
clonedList .printList ();
63
62
linkedList .printList ();
0 commit comments