-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathlist.go
More file actions
61 lines (54 loc) · 1.11 KB
/
list.go
File metadata and controls
61 lines (54 loc) · 1.11 KB
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
package linkedlist
import (
"cmp"
"unsafe"
)
type Node[T any] struct {
Next *Node[T]
Val T
}
func FakeHead[T cmp.Ordered](spt **Node[T]) *Node[T] {
//base := uintptr(unsafe.Pointer(spt))
//off := unsafe.Offsetof((*spt).Next)
//return (*Node[T])(unsafe.Pointer(base - off))
return (*Node[T])(unsafe.Pointer(spt))
}
func Merge[T cmp.Ordered](lst1, lst2 *Node[T]) (list *Node[T]) {
last := FakeHead(&list)
for {
last.Next = lst1
if lst2 == nil {
return list
}
for lst1 != nil && lst1.Val <= lst2.Val {
last, lst1 = lst1, lst1.Next
}
last.Next = lst2
if lst1 == nil {
return list
}
for lst2 != nil && lst1.Val > lst2.Val {
last, lst2 = lst2, lst2.Next
}
}
}
func IsSorted[T cmp.Ordered](head *Node[T]) bool {
if head == nil {
return true
}
for ; head.Next != nil; head = head.Next {
if head.Val > head.Next.Val {
return false
}
}
return true
}
func Reverse[T any](list *Node[T]) *Node[T] {
head := (*Node[T])(nil)
for list != nil {
node := list
list = list.Next
node.Next, head = head, node
}
return head
}