Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 11, 2015 19:18
Show Gist options
  • Save vderyagin/4647207 to your computer and use it in GitHub Desktop.
Save vderyagin/4647207 to your computer and use it in GitHub Desktop.
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()
}
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