-
Notifications
You must be signed in to change notification settings - Fork 2
/
00206-reverse_linked_list.go
60 lines (47 loc) · 1.02 KB
/
00206-reverse_linked_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
// 206: Reverse Linked List
// https://leetcode.com/problems/reverse-linked-list/
package main
import "fmt"
type ListNode struct {
val int
next *ListNode
}
type LinkedList struct {
head *ListNode
}
func llInput(head **ListNode, inputs []int) {
for i:=len(inputs)-1; i>=0; i-- {
node := &ListNode{inputs[i], *head}
*head = node
}
}
func llOutput(head *ListNode) {
for head != nil {
fmt.Print(head.val, " -> ")
head = head.next
}
fmt.Println("NULL")
}
// SOLUTION
func reverseList(head *ListNode) *ListNode {
if head == nil || head.next == nil {return head}
var previous *ListNode
current := head
next := head.next
for current != nil {
next = current.next;
current.next = previous
previous = current
current = next
}
return previous
}
func main() {
ll := LinkedList{}
// INPUT
li := []int{1,2,3,4,5}
llInput(&ll.head, li)
// OUTPUT
result := reverseList(ll.head)
llOutput(result)
}