Last active
December 11, 2015 19:18
-
-
Save vderyagin/4647207 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sorted_linked_list | |
import ( | |
"bytes" | |
"fmt" | |
) | |
type list struct { | |
head *node | |
} | |
type node struct { | |
value int | |
next *node | |
} | |
func New() *list { | |
return new(list) | |
} | |
func (l *list) Add(number int) { | |
if l.head == nil || l.head.value > number { | |
l.head = &node{ | |
value: number, | |
next: l.head, | |
} | |
return | |
} | |
n := l.head | |
for n.next != nil && n.next.value < number { | |
n = n.next | |
} | |
n.next = &node{ | |
value: number, | |
next: n.next, | |
} | |
} | |
func (l *list) String() string { | |
var s bytes.Buffer | |
s.WriteString("[ ") | |
for n := l.head; n != nil; n = n.next { | |
fmt.Fprintf(&s, "%d ", n.value) | |
} | |
s.WriteString("]") | |
return s.String() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sorted_linked_list | |
import "testing" | |
func Test(t *testing.T) { | |
l := New() | |
if s := l.String(); s != "[ ]" { | |
t.Errorf("%s != %s", s, "[ ]") | |
} | |
l.Add(3) | |
if s := l.String(); s != "[ 3 ]" { | |
t.Errorf("%s != %s", s, "[ 3 ]") | |
} | |
l.Add(8) | |
if s := l.String(); s != "[ 3 8 ]" { | |
t.Errorf("%s != %s", s, "[ 3 8 ]") | |
} | |
l.Add(4) | |
if s := l.String(); s != "[ 3 4 8 ]" { | |
t.Errorf("%s != %s", s, "[ 3 4 8 ]") | |
} | |
l.Add(0) | |
if s := l.String(); s != "[ 0 3 4 8 ]" { | |
t.Errorf("%s != %s", s, "[ 0 3 4 8 ]") | |
} | |
l.Add(86) | |
if s := l.String(); s != "[ 0 3 4 8 86 ]" { | |
t.Errorf("%s != %s", s, "[ 0 3 4 8 86 ]") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment