Created
August 14, 2013 16:31
-
-
Save pokstad/6232815 to your computer and use it in GitHub Desktop.
Singly Linked List in GO
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 main | |
import "fmt" | |
type LLNode struct { | |
data string | |
next *LLNode | |
} | |
type LList struct { | |
size int | |
head *LLNode | |
tail *LLNode | |
} | |
func (list *LList) ShowList() { | |
node := list.head | |
count := 0 | |
fmt.Printf("Link list %p size %d head %p tail %p:\n", list, list.size, list.head, list.tail) | |
for { | |
count++ | |
fmt.Printf("%d %p %s\n", count, node, node.data) | |
if (node.IsTail()) { | |
return | |
} else { | |
node = node.next | |
} | |
} | |
} | |
func (list *LList) InitList() (head *LLNode) { | |
list.head = nil | |
list.tail = list.head | |
list.size = 1 | |
return list.head | |
} | |
func (head *LLNode) DestroyList() error { | |
return nil | |
} | |
func (list *LList) InsertNext(cursor *LLNode, data string) (*LLNode) { | |
// 3 cases exist: inserting at the head, middle, and tail of list | |
newNode := new(LLNode) | |
newNode.data = data | |
// handle head case | |
if (cursor == nil) { | |
newNode.next = list.head | |
list.head = newNode | |
} else { | |
newNode.next = cursor.next | |
cursor.next = newNode | |
} | |
// handle tail case | |
if (newNode.next == nil) { | |
list.tail = newNode | |
} | |
list.size++ | |
return newNode | |
} | |
func (list *LList) RemoveNext(cursor *LLNode) (*LLNode) { | |
return nil | |
} | |
func (head *LLNode) Size() error { | |
return nil | |
} | |
func (node *LLNode) IsHead() bool { | |
return true | |
} | |
func (node *LLNode) IsTail() bool { | |
if (node.next == nil) { | |
return true | |
} | |
return false | |
} | |
func (node *LLNode) Data() error { | |
return nil | |
} | |
func (node *LLNode) Next() error { | |
return nil | |
} | |
func main() { | |
fmt.Println("Link list tutorial") | |
list := new(LList) | |
cursor := list.InitList() | |
fmt.Printf("Link list header pointer at: %p\n", &list) | |
cursor = list.InsertNext(cursor, "test") | |
cursor = list.InsertNext(cursor, "test2") | |
cursor = list.InsertNext(cursor, "test3") | |
cursor = list.InsertNext(nil, "test0") | |
list.ShowList() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment