Skip to content

Commit 47c1177

Browse files
committed
clone linked list with two approaches
1 parent 628956a commit 47c1177

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

Two Pointers/cloneLinkedlist.java

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
int val;
5+
Node next;
6+
Node random;
7+
8+
public Node(int val) {
9+
this.val = val;
10+
this.next = null;
11+
this.random = null;
12+
}
13+
}
14+
*/
15+
16+
// O(N) time, O(N) space
17+
class Solution {
18+
public Node copyRandomList(Node head) {
19+
if (head == null) {
20+
return null;
21+
}
22+
23+
// mapping original node to its clone
24+
HashMap<Node, Node> hm = new HashMap<>();
25+
26+
// giving all nodes their clone in the mapping
27+
Node cur = head;
28+
while(cur != null) {
29+
hm.put(cur, new Node(cur.val)); //(node, node_clone)
30+
cur = cur.next;
31+
}
32+
33+
//resetting cur pointer to head of the original list
34+
// giving all clones their next and random ptr
35+
cur = head;
36+
while(cur != null) {
37+
hm.get(cur).next = hm.get(cur.next);
38+
hm.get(cur).random = hm.get(cur.random);
39+
cur = cur.next;
40+
}
41+
return hm.get(head);
42+
}
43+
}
44+
45+
// O(N) time, O(1) space
46+
47+
/*
48+
// Definition for a Node.
49+
class Node {
50+
int val;
51+
Node next;
52+
Node random;
53+
54+
public Node(int val) {
55+
this.val = val;
56+
this.next = null;
57+
this.random = null;
58+
}
59+
}
60+
*/
61+
class Solution {
62+
public Node copyRandomList(Node head) {
63+
Node cur = head;
64+
Node next = null;
65+
66+
// 1st pass, just connect original nodes to its clone
67+
while(cur != null) {
68+
next = cur.next; //storing next value of original node, so that we don't lose it
69+
Node copyNode = new Node(cur.val);
70+
cur.next = copyNode;
71+
copyNode.next = next;
72+
// advancing to next node in original list
73+
cur = next;
74+
}
75+
// 2nd pass, assign clone its random mapping
76+
cur = head;
77+
while(cur != null) {
78+
if (cur.random != null) {
79+
cur.next.random = cur.random.next; // since we want random's clone
80+
}
81+
cur = cur.next.next;
82+
}
83+
//3rd pass, removing the next value of original nodes
84+
cur = head;
85+
Node dummyHead = new Node(0);
86+
Node cloneListTail = dummyHead;
87+
Node copy = null;
88+
while(cur != null) {
89+
next = cur.next.next; //next in the original node
90+
// saving cur's clone
91+
copy = cur.next;
92+
// appending copy to final list tail
93+
cloneListTail.next = copy;
94+
cloneListTail = copy;
95+
96+
cur.next = next; // restoring original cur's next value
97+
98+
cur = next; // advancing curr to next in the original node
99+
100+
}
101+
return dummyHead.next;
102+
}
103+
}

0 commit comments

Comments
 (0)