/
list.go
66 lines (54 loc) · 1016 Bytes
/
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
61
62
63
64
65
66
package value
import (
"bytes"
)
type List struct {
head *ListNode
len_ int
}
type ListNode struct {
val Value
next *ListNode
}
func NewList(nodes []Value) *List {
if len(nodes) == 0 {
return &List{nil, 0}
}
var dummy ListNode
cur := &dummy
for _, node := range nodes {
cur.next = &ListNode{node, nil}
cur = cur.next;
}
return &List{dummy.next, len(nodes)}
}
func (self *List) Car() Value {
if self.head != nil {
return self.head.val
}
return nil
}
func (self *List) Cdr() Value {
if self.head.next != nil {
return &List{self.head.next, self.len_ - 1}
}
return &List{nil, 0}
}
func (self *List) Empty() bool {
if self.head == nil {
return true
}
return false
}
func (self *List) String() string {
var buf bytes.Buffer
buf.WriteRune('(')
for cur := self.head; cur != nil; cur = cur.next {
if cur != self.head {
buf.WriteRune(' ')
}
buf.WriteString(cur.val.String())
}
buf.WriteRune(')')
return buf.String()
}