Skip to content

Instantly share code, notes, and snippets.

@IceWreck
Created September 28, 2020 06:28
Show Gist options
  • Save IceWreck/a90983129549ff60108aac87d3c7c8fa to your computer and use it in GitHub Desktop.
Save IceWreck/a90983129549ff60108aac87d3c7c8fa to your computer and use it in GitHub Desktop.
Stack implemented in go using a linked list
// Stack implemented in Go without using any std lib function
// Uses linked lists instead of a slice or something
package main
import (
"errors"
"fmt"
)
// node is a single element of the list
type node struct {
value int
next *node
}
// Stack -
type Stack struct {
head *node
}
// Push inserts element into the stack (top of the list)
func (l *Stack) Push(val int) {
newNode := &node{value: val}
if l.head == nil {
l.head = newNode
} else {
currentNode := l.head
newNode.next = currentNode
l.head = newNode
}
}
// Pop removes the topmost element
func (l *Stack) Pop() (int, error) {
if l.head != nil {
currentNode := l.head
// if there is one element only
if currentNode.next == nil {
l.head = nil
return currentNode.value, nil
}
// if there are more than one element
l.head = currentNode.next
return currentNode.value, nil
}
err := errors.New("Error: Can't pop, stack is empty")
fmt.Println(err)
return 0, err
}
// Peek returns the topmost element without removing it or error if stack is empty
func (l *Stack) Peek() (int, error) {
currentNode := l.head
if currentNode != nil {
return currentNode.value, nil
}
return 0, errors.New("Error: Stack empty")
}
// Display the list
func (l *Stack) Display() {
fmt.Print("Stack is : ")
if l.head != nil {
currentNode := l.head
fmt.Print(currentNode.value, " ")
for currentNode.next != nil {
currentNode = currentNode.next
fmt.Print(currentNode.value, " ")
}
}
fmt.Println()
}
func main() {
var dll Stack
dll.Push(8)
dll.Push(5)
dll.Push(6)
temp, err := dll.Peek()
if err == nil {
fmt.Println("Peeking ", temp)
}
dll.Push(7)
dll.Display()
value, err := dll.Pop()
if err == nil {
fmt.Println(value, " was popped from the stack.")
}
value, err = dll.Pop()
if err == nil {
fmt.Println(value, " was popped from the stack.")
}
value, err = dll.Pop()
if err == nil {
fmt.Println(value, " was popped from the stack.")
}
value, err = dll.Pop()
if err == nil {
fmt.Println(value, " was popped from the stack.")
}
value, err = dll.Pop()
if err == nil {
fmt.Println(value, " was popped from the stack.")
}
temp, err = dll.Peek()
if err == nil {
fmt.Println("Peeking ", temp)
} else {
fmt.Println(err)
}
dll.Display()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment