Java Data Structure Cheat Sheet - Stack

Stack exists as a class (not as an interface or abstract class) in Java.

https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html


Here are the three main methods:

  • E peek()
  • E pop()
  • E push(E item)

They are all O(1).


Example:


import java.util.Stack;


public class StackExample {


  public static void main(String[] args) {

    Stack<Integer> s = new Stack<Integer>();


    s.push(1); // add is also available as Vector

    s.push(2);

    s.push(3);


    System.out.println(s.peek()); // 3


    while (!s.empty()) { // isEmpty() is also available as Vector

      int n = s.pop();

      System.out.println(n); // 3, 2, 1

    }


    // System.out.println(s.peek()); // java.util.EmptyStackException is called

  }

}


Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

PyCharm: Quick Start