Commits

Michael  committed 1b0b2a1

lists in go

  • Participants
  • Parent commits 9c2239a

Comments (0)

Files changed (3)

File go/list/Makefile

+include $(GOROOT)/src/Make.$(GOARCH)
+TARG = mylist
+GOFILES = list.go
+include $(GOROOT)/src/Make.pkg

File go/list/list.go

+package mylist
+
+import (
+	"fmt"
+	"os"
+)
+
+type IntList struct {
+	x int
+	next *IntList
+}
+
+func (l *IntList) head() int {
+	if (l == nil) {
+		fmt.Fprintf(os.Stderr, "empty list\n")
+		os.Exit(1)
+	}
+	return l.x
+}
+
+func (l *IntList) tail() *IntList {
+	if (l == nil) {
+		fmt.Fprintf(os.Stderr, "empty list\n")
+		os.Exit(1)
+	}
+	return l.next
+}
+
+func (l *IntList) push(x int) {
+	l.next = l
+	l.x = x
+}
+
+func (l *IntList) pop() int {
+	x := l.x
+	l = l.next
+	return x
+}
+
+func fromSlice(a []int) *IntList {
+	l := new(IntList)
+	for i := 0; i < len(a); i++ {
+		l.push(a[i])
+	}
+	return l
+}

File go/list/list_test.go

+package mylist
+
+import (
+	"fmt"
+	"testing"
+)
+
+func TestMain(t *testing.T) {
+	l := fromSlice([]int{1,2,3,5})
+	fmt.Printf("%d\n", l.head())
+}