-
Notifications
You must be signed in to change notification settings - Fork 1
/
list.go
93 lines (86 loc) · 1.67 KB
/
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
package utils
import (
"bytes"
"strconv"
)
// ListNode is a node structure in a list
type ListNode struct {
Val int
Next *ListNode
}
func (l *ListNode) String() string {
var buf bytes.Buffer
for l != nil {
buf.WriteString(strconv.FormatInt(int64(l.Val), 10))
l = l.Next
if l != nil {
buf.WriteString("->")
}
}
return buf.String()
}
// IsEqualList checks l1 == l2
func IsEqualList(h1, h2 *ListNode) bool {
return h1.String() == h2.String()
}
// ConstructFromSlice returns a *ListNode built by s
func ConstructFromSlice(s []int) *ListNode {
// var head, prev *ListNode
// for i, c := range s {
// if i == 0 {
// head = &ListNode{
// Val: c,
// Next: nil,
// }
// prev = head
// } else {
// cur := &ListNode{
// Val: c,
// Next: nil,
// }
// if prev != nil {
// prev.Next = cur
// }
// prev = cur
// }
// }
// return head
dummy := &ListNode{}
pre := dummy
for i := range s {
pre.Next = &ListNode{Val: s[i]}
pre = pre.Next
}
return dummy.Next
}
// ConstructFromSliceWithCycle returns a ListNode with cycle.
func ConstructFromSliceWithCycle(s []int) *ListNode {
// here we assume the value of each node is unique.
set := make(map[int]*ListNode, len(s))
dummy := &ListNode{}
pre := dummy
for _, v := range s {
if node, exists := set[v]; exists {
pre.Next = node
} else {
pre.Next = &ListNode{Val: v}
}
pre = pre.Next
}
return dummy.Next
}
// ReverseList return the reversed list
func ReverseList(head *ListNode) *ListNode {
if head == nil {
return head
}
next := head.Next
head.Next = nil
for next != nil {
tmp := next.Next
next.Next = head
head = next
next = tmp
}
return head
}