Skip to content

Commit

Permalink
add linked lists stack and queue examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Nishi Davidson authored and Nishi Davidson committed Apr 17, 2020
1 parent 06e60bb commit 3bb441e
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 6 deletions.
18 changes: 12 additions & 6 deletions llist-create.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,18 @@ func main() {

l := List{}

l.InsertBack("15")
l.InsertBack("15")
l.InsertBack("10")
l.InsertBack("10")
l.InsertBack("22")
l.InsertBack("10")
l.InsertBack("(")
l.InsertBack(")")
l.InsertBack("[")
l.InsertBack("{")
l.InsertBack("{")
l.InsertBack("{")
l.InsertBack("[")
l.InsertBack("]")
l.InsertBack("}")
l.InsertBack("}")
l.InsertBack("}")
l.InsertBack("]")

fmt.Printf("head: %v\n", l.head.value)
fmt.Printf("tail: %v\n", l.tail.value)
Expand Down
60 changes: 60 additions & 0 deletions queue.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"fmt"
)

type List struct {
head *Node
tail *Node
}

type Node struct {
value int
prev *Node
next *Node
}

func main() {

l := List{}

l.QueueElem(10)
l.QueueElem(40)
l.QueueElem(1)
l.QueueElem(15)
l.QueueElem(80)

l.Dequeue(3)

}

func (l *List) QueueElem(x int) {
n := &Node{
value: x,
prev: l.tail,
}

if l.tail != nil {
l.tail.next = n
}
l.tail = n

if l.head == nil {
l.head = n
}

}

func (l *List) Dequeue(x int) {
if l.head == nil {
fmt.Println("Nil list")
return
}

for l.head != nil {
fmt.Printf("value: %d\n", l.head.value)
l.head = l.head.next
}

}
60 changes: 60 additions & 0 deletions stack.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"fmt"
)

type List struct {
head *Node
tail *Node
}

type Node struct {
value int
next *Node
prev *Node
}

func main() {

l := List{}

l.PushElem(12)
l.PushElem(1)
l.PushElem(52)
l.PushElem(14)
l.PushElem(6)
l.PushElem(33)

l.PopElem()
}

func (l *List) PushElem(x int) {
n := &Node{
value: x,
next: l.head,
}

if l.head != nil {
l.head.prev = n
}
l.head = n

if l.tail == nil {
l.tail = n
}

}

func (l *List) PopElem() {

for l.head != nil {
fmt.Printf("value: %d\n", l.head.value)
l.head = l.head.next
}

if l.head == nil {
fmt.Println("Nil")
}

}

0 comments on commit 3bb441e

Please sign in to comment.