-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.go
99 lines (79 loc) · 1.52 KB
/
linkedlist.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
96
97
98
99
package practice
// Can be used as a stupid array,
// a queue, or a stack.
type DoublyLinkedListNode struct {
value int
prev *DoublyLinkedListNode
next *DoublyLinkedListNode
}
type DoublyLinkedList struct {
Size int
first *DoublyLinkedListNode
last *DoublyLinkedListNode
}
func (l *DoublyLinkedList) IsEmpty() bool {
return l.Size == 0
}
func (l *DoublyLinkedList) Add(value int) {
l.AddLast(value)
}
// Push
func (l *DoublyLinkedList) AddLast(value int) {
defer func() { l.Size++ }()
n := DoublyLinkedListNode{value, nil, nil}
if l.IsEmpty() {
l.first = &n
l.last = &n
return
}
l.last.next = &n
n.prev = l.last
l.last = &n
}
// Shift
func (l *DoublyLinkedList) AddFirst(value int) {
defer func() { l.Size++ }()
n := DoublyLinkedListNode{value, nil, nil}
if l.IsEmpty() {
l.first = &n
l.last = &n
return
}
l.first.prev = &n
n.next = l.first
l.first = &n
}
func (l *DoublyLinkedList) Remove() (int, bool) {
v, ok := l.RemoveFirst()
return v, ok
}
// Pop
func (l *DoublyLinkedList) RemoveLast() (int, bool) {
if l.IsEmpty() {
return 0, false
}
defer func() { l.Size-- }()
n := l.last
newLast := l.last.prev
n.prev = nil
if newLast != nil {
newLast.next = nil
}
l.last = newLast
return n.value, true
}
// Unshift
func (l *DoublyLinkedList) RemoveFirst() (int, bool) {
if l.IsEmpty() {
return 0, false
}
defer func() { l.Size-- }()
n := l.first
newFirst := l.first.next
n.next = nil
if newFirst != nil {
newFirst.prev = nil
}
l.first = newFirst
return n.value, true
}