Golang stack implementation

package main

import (
	"container/list"
	"errors"
	"fmt"
)

// Stack is a list that can only perform two operations: push and pop
type Stack struct {
	items list.List
}

// push() method inserts new element at the top of the stack
func (stack *Stack) push(str string) {
	stack.items.PushBack(str)
}

// pop() method removes the element at the top of the stack
func (stack *Stack) pop() (string, error) {
	if stack.items.Back() == nil {
		return "", errors.New("Empty")
	}
	lastVal := stack.items.Back().Value.(string) // get the value of last element
	stack.items.Remove(stack.items.Back())       // remove the last element
	return lastVal, nil
}

func main() {
	stack := &Stack{}
	stack.push("1")
	stack.push("2")
	fmt.Println(stack.pop())
	fmt.Println(stack.pop())
	fmt.Println(stack.pop())
}

Leave a Reply