From 4f24c10a4cb81ff260cecd56a79c2481b151ed35 Mon Sep 17 00:00:00 2001 From: Swim Systems Date: Sun, 15 Oct 2017 13:08:32 +0200 Subject: [PATCH] Add linked list implementation in Go --- linked_list/linked_list.go | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 linked_list/linked_list.go diff --git a/linked_list/linked_list.go b/linked_list/linked_list.go new file mode 100644 index 000000000..e837954fd --- /dev/null +++ b/linked_list/linked_list.go @@ -0,0 +1,53 @@ +package main + +import "fmt" + +type Node struct { + prev *Node + next *Node + key interface{} +} + +type LinkedList struct { + head *Node + tail *Node +} + +func (L *LinkedList) Insert(key interface{}) { + list := &Node{ + next: L.head, + key: key, + } + if L.head != nil { + L.head.prev = list + } + L.head = list + + l := L.head + for l.next != nil { + l = l.next + } + L.tail = l +} + +func (l *LinkedList) Show() { + list := l.head + for list != nil { + fmt.Printf("%+v", list.key) + if list.next != nil { + fmt.Printf(" --> ") + } + list = list.next + } + fmt.Println() +} + +func main() { + l := LinkedList{} + l.Insert(1) + l.Insert(2) + l.Insert(3) + l.Insert(4) + l.Insert(5) + l.Show() +}