-
Notifications
You must be signed in to change notification settings - Fork 2
/
lstrev.go
57 lines (46 loc) · 859 Bytes
/
lstrev.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
package lstrev
type ListNode struct {
Value int
Next *ListNode
}
func ReverseListRec(head *ListNode) *ListNode {
return reverse(nil, head)
}
func reverse(prev *ListNode, curr *ListNode) *ListNode {
if curr == nil {
return prev
}
next := curr.Next
curr.Next = prev
return reverse(curr, next)
}
func ReverseListItr(head *ListNode) *ListNode {
var prev, next *ListNode
for curr := head; curr != nil; prev, curr = curr, next {
next = curr.Next
curr.Next = prev
}
return prev
}
func NewList(s []int) *ListNode {
if len(s) == 0 {
return nil
}
h := &ListNode{s[0], nil}
n := h
for _, v := range s[1:] {
n.Next = &ListNode{v, nil}
n = n.Next
}
return h
}
func (h *ListNode) ToSlice() []int {
if h == nil {
return []int{}
}
s := make([]int, 0)
for n := h; n != nil; n = n.Next {
s = append(s, n.Value)
}
return s
}