-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-linkedlist.go
More file actions
65 lines (52 loc) · 995 Bytes
/
reverse-linkedlist.go
File metadata and controls
65 lines (52 loc) · 995 Bytes
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
package main
import "fmt"
// type ListNode struct {
// Val int
// Next *ListNode
// }
type LinkedList struct {
head *ListNode
len int
}
func (list *LinkedList) insert(data int) {
if list.head == nil {
list.head = &ListNode{data, nil}
list.len++
} else {
itr := list.head
for ; itr.Next != nil; itr = itr.Next {
}
itr.Next = &ListNode{data, nil}
list.len++
}
}
func (list *LinkedList) list() []int {
nums := []int{}
next := list.head
for ; next != nil; next = next.Next {
nums = append(nums, next.Val)
}
return nums
}
func (list *LinkedList) reverse() {
var newhead *ListNode = nil
for list.head != nil {
next := list.head.Next
list.head.Next = newhead
newhead = list.head
list.head = next
}
list.head = newhead
}
func main_reverse_linked_list() {
var list LinkedList
fmt.Println(list)
// list.insert(4)
nums := []int{3, 6, 8, 10}
for _, e := range nums {
list.insert(e)
}
list.reverse()
numsl := list.list()
fmt.Println(numsl)
}