-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_list_test.go
77 lines (59 loc) · 1.29 KB
/
reverse_list_test.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
/*
Problem:
- Given the head of a singly linked list, write a function to return the
new head of the reversed linked list.
Approach:
- Iterate through the linked list and at each step, reverse the current
node by pointing it to the previous node before moving on.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/pcaruana/algo/common"
)
func TestReverseList(t *testing.T) {
t0 := common.NewListNode(0)
t1 := common.NewListNode(1)
t2 := common.NewListNode(1)
t2.AddNext(2)
t3 := common.NewListNode(1)
t3.AddNext(2)
t3.AddNext(3)
tests := []struct {
in *common.ListNode
expected []int
}{
{t0, []int{0}},
{t1, []int{1}},
{t2, []int{2, 1}},
{t3, []int{3, 2, 1}},
}
for _, tt := range tests {
h := reverseList(tt.in)
common.Equal(
t,
tt.expected,
common.LinkedListToSlice(h),
)
}
}
func reverseList(head *common.ListNode) *common.ListNode {
if head == nil || head.Next == nil {
return head
}
current := head
var previous, next *common.ListNode
for current != nil {
// temporarily store the next node.
next = current.Next
// reverse the current node.
current.Next = previous
// point the previous node to the current node.
previous = current
// move on to the next node
current = next
}
return previous
}