-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly.go
59 lines (52 loc) · 1.05 KB
/
doubly.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
package doubly
type List[T any] struct {
head *ListNode[T]
}
// ListNode[T any] defines a doubly linked list node
type ListNode[T any] struct {
Val T
Prev *ListNode[T]
Next *ListNode[T]
}
// ListOf[T any] is a variadic constructor of List
func ListOf[T any](nodes ...T) *List[T] {
if len(nodes) == 0 {
return nil
}
head := &ListNode[T]{Val: nodes[0]}
tail := head
for i := 1; i < len(nodes); i++ {
tail.Next = &ListNode[T]{Val: nodes[i], Prev: tail}
tail = tail.Next
}
return &List[T]{head: head}
}
func (l *List[T]) Head() *ListNode[T] {
return l.head
}
func (l *List[T]) Tail() *ListNode[T] {
if l.head == nil {
return nil
}
n := l.head
for n.Next != nil {
n = n.Next
}
return n
}
// Find takes a selector func and returns the first match using that func or nil
func (l *List[T]) Find(match func(item T) bool) *ListNode[T] {
h := l.head
for h != nil && !match(h.Val) {
h = h.Next
}
return h
}
func (l *List[T]) Insert(item T) {
h := l.head
n := &ListNode[T]{Val: item, Next: h}
l.head = n
if h != nil {
h.Prev = l.head
}
}