-
Notifications
You must be signed in to change notification settings - Fork 5
/
copy_list_with_random_pointer.go
70 lines (61 loc) · 1.32 KB
/
copy_list_with_random_pointer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
type Node struct {
Val int
Next *Node
Random *Node
}
func insertAtTail(head **Node, tail **Node, data int) {
temp := &Node{Val: data}
if *head == nil {
*head = temp
*tail = temp
return
}
(*tail).Next = temp
*tail = temp
}
func copyRandomList(head *Node) *Node {
if head == nil {
return nil
}
// Step 1: Create a clone linked list
temp := head
var cloneHead *Node
var cloneTail *Node
for temp != nil {
insertAtTail(&cloneHead, &cloneTail, temp.Val)
temp = temp.Next
}
// Step 2: Connect links between clone and original list
cloneNode := cloneHead
originalNode := head
for originalNode != nil && cloneNode != nil {
originalNext := originalNode.Next
originalNode.Next = cloneNode
originalNode = originalNext
cloneNext := cloneNode.Next
cloneNode.Next = originalNode
cloneNode = cloneNext
}
// Step 3: Connect random pointers
temp = head
for temp != nil {
if temp.Random != nil {
temp.Next.Random = temp.Random.Next
}
temp = temp.Next.Next
}
// Revert Step 2
originalNode = head
cloneNode = cloneHead
for originalNode != nil && cloneNode != nil {
originalNode.Next = cloneNode.Next
originalNode = originalNode.Next
if originalNode != nil {
cloneNode.Next = originalNode.Next
}
cloneNode = cloneNode.Next
}
// Return the cloned head
return cloneHead
}