DEV Community

Cover image for Algorithms and Data Structures - Stack
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Algorithms and Data Structures - Stack

This article was originally published on bmf-tech.com.

Overview

Referring to the Algorithm Encyclopedia, we learn about algorithms and data structures.

The implementation is also available on github - bmf-san/road-to-algorithm-master.

Stack

  • A structure where data is lined up in such a way that only the most recent data can be accessed
    • LIFO (Last In First Out)
    • Last in, first out
  • A convenient structure when you always want to access the most recent data
  • Adding data is called Push, and removing data is called Pop.
    • Other operations include Dup, Peek, Swap (or Exchange), and Rotate.
    • cf. Wikipedia - Stack

Computational Time

Depends on the implementation form such as arrays or linked lists.

Implementation

package main

// Stack is a stack.
type Stack struct {
    nodes []*Node
}

// Node is a item of a stack.
type Node struct {
    value string
}

// newStack create a Stack.
func newStack() *Stack {
    return &Stack{}
}

// push adds an node to the top of the stack.
func (s *Stack) push(n *Node) {
    s.nodes = append(s.nodes[:len(s.nodes)], n)
}

// pop removes an node from the top of the stack.
func (s *Stack) pop() {
    s.nodes = s.nodes[:len(s.nodes)-1]
}

Enter fullscreen mode Exit fullscreen mode
  • If you are familiar with Go slices, there should be no particularly difficult parts
  • Notes
    • Image from iOS (1)

References

Top comments (0)