How to implement a stack in Java?

by elwin_wilderman , in category: Java , a year ago

How to implement a stack in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by kathryne.gleichner , a year ago

@elwin_wilderman 

A stack is a data structure that operates on a last-in, first-out (LIFO) basis. You can implement a stack in Java using an array or a linked list. Here is an example of a stack implemented using an array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Stack {
  private int[] arr;
  private int top;

  public Stack(int size) {
    arr = new int[size];
    top = -1;
  }

  public void push(int value) {
    if (top == arr.length - 1) {
      throw new StackOverflowError();
    }
    arr[++top] = value;
  }

  public int pop() {
    if (top == -1) {
      throw new NoSuchElementException();
    }
    return arr[top--];
  }

  public int peek() {
    if (top == -1) {
      throw new NoSuchElementException();
    }
    return arr[top];
  }

  public boolean isEmpty() {
    return top == -1;
  }

  public int size() {
    return top + 1;
  }
}


Here is an example of a stack implemented using a linked list:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Stack {
  private static class Node {
    private int data;
    private Node next;

    private Node(int data) {
      this.data = data;
    }
  }

  private Node top;

  public void push(int value) {
    Node node = new Node(value);
    node.next = top;
    top = node;
  }

  public int pop() {
    if (top == null) {
      throw new NoSuchElementException();
    }
    int value = top.data;
    top = top.next;
    return value;
  }

  public int peek() {
    if (top == null) {
      throw new NoSuchElementException();
    }
    return top.data;
  }

  public boolean isEmpty() {
    return top == null;
  }
}


You can use the stack in the same way as you would use a stack in real life. For example, you can "push" items onto the stack and "pop" items off the stack. You can also check if the stack is empty or peek at the top element without removing it.