-
Notifications
You must be signed in to change notification settings - Fork 1
/
Leetcode 707 Design Linked List.go
87 lines (85 loc) · 1.94 KB
/
Leetcode 707 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
type Node struct {
Val int
next *Node
}
type MyLinkedList struct {
head *Node
length int
}
func Constructor() MyLinkedList {
return MyLinkedList{head : nil, length : 0}
}
func (this *MyLinkedList) Get(index int) int {
if index < 0 || index >= this.length {
return -1
} else {
curr := this.head
for i := 0; i < index; i++ {
curr = curr.next
}
return curr.Val
}
}
func (this *MyLinkedList) AddAtHead(val int) {
this.head = &Node{Val: val, next: this.head}
this.length++
}
func (this *MyLinkedList) AddAtTail(val int) {
if this.length == 0 {
this.AddAtHead(val)
return
}
curr := this.head
for i := 0; i < this.length-1; i++ {
curr = curr.next
}
curr.next = &Node{Val: val}
this.length++
return
}
func (this *MyLinkedList) AddAtIndex(index int, val int) {
if index < 0 || index > this.length {
return
}
if index == 0 {
this.AddAtHead(val)
return
} else if index == this.length {
this.AddAtTail(val)
return
} else {
curr := this.head
for i := 0; i < index-1; i++ {
curr = curr.next
}
curr.next = &Node{Val: val, next: curr.next}
this.length++
return
}
}
func (this *MyLinkedList) DeleteAtIndex(index int) {
if index < 0 || index >= this.length {
return
} else if index == 0 {
this.head = this.head.next
this.length--
return
} else {
curr := this.head
for i := 0; i < index-1; i++ {
curr = curr.next
}
curr.next = curr.next.next
this.length--
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);
*/