-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse.go
74 lines (58 loc) · 1.16 KB
/
reverse.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
package reverse
import (
"errors"
"fmt"
)
// List is a definition of linked list.
type List struct {
Val byte
Next *List
}
// Init initializes a linked list.
func Init(s []byte) (*List, error) {
if string(s) == "" {
return nil, errors.New("list is empty")
}
head := &List{s[0], nil}
curr := head
for i := 1; i < len(s); i++ {
node := &List{s[i], nil}
curr.Next = node
curr = node
}
return head, nil
}
// Print returns a linked list as a string to print.
func Print(list *List) string {
result := ""
curr := list
for curr != nil {
result += fmt.Sprintf("%c", curr.Val)
curr = curr.Next
}
return result
}
// LinkedList reverses a linked list.
func LinkedList(node *List) (*List, error) {
if node == nil {
return nil, errors.New("list is empty")
}
var curr, prev, next *List = node, nil, nil
for curr != nil {
next = curr.Next
curr.Next = prev
prev = curr
curr = next
}
return prev, nil
}
// String reverses a string in bytes.
func String(s []byte) ([]byte, error) {
if string(s) == "" {
return nil, errors.New("string is empty")
}
for i := 0; i < len(s)/2; i++ {
s[i], s[len(s)-i-1] = s[len(s)-i-1], s[i]
}
return s, nil
}