-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathserialization.go
67 lines (55 loc) · 1.15 KB
/
serialization.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
package linkedlist
import (
"strconv"
"strings"
)
const separator = `->`
// Node is a link in a singly linked list that stores integers.
type Node struct {
// Val is the value of the node
Val int
// Next is a link to the next node
Next *Node
}
// NewNode returns a new node.
func NewNode(v int) *Node {
return &Node{
Val: v,
Next: nil,
}
}
// Serialize solves the problem in O(n) time and O(1) space.
func Serialize(node *Node) string {
if node == nil {
return ""
}
output := strconv.Itoa(node.Val) + separator
for node.Next != nil {
node = node.Next
output += strconv.Itoa(node.Val) + separator
}
return strings.TrimSuffix(output, separator)
}
// Deserialize solves the problem in O(n) time and O(1) space.
func Deserialize(stringRepresentation string) *Node {
if stringRepresentation == "" {
return nil
}
var cur, last *Node
broken := strings.Split(stringRepresentation, separator)
for i := len(broken) - 1; i >= 0; i-- {
last = cur
cur = NewNode(atoi(broken[i]))
if last != nil {
cur.Next = last
}
}
return cur
}
func atoi(number string) int {
i, err := strconv.Atoi(number)
if err != nil {
return -1
}
return i
}