-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0707-design-linked-list.go
95 lines (80 loc) · 1.65 KB
/
0707-design-linked-list.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
type Node struct {
val int
prev *Node
next *Node
}
func NewNode(val int, prev, next *Node) *Node {
return &Node{
val: val,
prev: prev,
next: next,
}
}
type MyLinkedList struct {
head *Node
tail *Node
}
func Constructor() MyLinkedList {
head := NewNode(-1, nil, nil)
tail := NewNode(-1, head, nil)
head.next = tail
return MyLinkedList{
head: head,
tail: tail,
}
}
func (this *MyLinkedList) Get(index int) int {
cur := this.head.next
for cur != nil && index > 0 {
cur = cur.next
index--
}
if cur != nil && cur != this.tail && index == 0 {
return cur.val
}
return -1
}
func (this *MyLinkedList) AddAtHead(val int) {
node := NewNode(val, this.head, this.head.next)
this.head.next.prev = node
this.head.next = node
}
func (this *MyLinkedList) AddAtTail(val int) {
node := NewNode(val, this.tail.prev, this.tail)
this.tail.prev.next = node
this.tail.prev = node
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
cur := this.head.next
for cur.next != nil && index > 0 {
cur = cur.next
index--
}
if index == 0 {
node := NewNode(val, cur.prev, cur)
cur.prev.next = node
cur.prev = node
}
return
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
cur := this.head.next
for cur.next != nil && index > 0 {
cur = cur.next
index--
}
if index == 0 && cur != nil && cur != this.tail {
prev, next := cur.prev, cur.next
prev.next, next.prev = next, prev
}
return
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Get(index);
* obj.AddAtHead(val);
* obj.AddAtTail(val);
* obj.AddAtIndex(index,val);
* obj.DeleteAtIndex(index);
*/