Skip to main content

7. Stack Implementation

 

Stack Implementation

The following Stack class in Java consists of following methods:

  1. push(int value): Inserts a data item at the top of the stack.
  2. pop(): Removes the top most data item from the stack.
  3. peek(): Returns the topmost element of the stack.
  4. isEmpty(): Returns true if the stack is empty.
  5. isFull(): Returns true is the stack is full.

The data members of Stack class consists:

  1. top: Private member to track the topmost element of the stack.
  2. size: Private member to track the maximum capacity of the stack.
  3. arr[]: Private array to implement the stack.

Static Implementation

class Stack {

    private int top;
    private int size;
    private int arr[];

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

    boolean push(int value) {
        if (top == size - 1)
            return false;
        top++;
        arr[top] = value;
        return true;
    }

    boolean pop() {
        if (top == -1)
            return false;
        top--;
        return true;
    }

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

    boolean isEmpty() {
        if (top == -1)
            return true;
        return false;
    }

    boolean isFull() {
        if (top == size - 1)
            return true;
        return false;
    }
}

Dynamic Implementation

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        next = null;
    }
}

class Stack {
    private Node top;

    Stack() {
        top = null;
    }

    boolean push(int value) {
        Node node = new Node(value);
        if (top != null)
            node.next = top;
        top = node;
        return true;
    }

    boolean pop() {
        if (top == null)
            return false;
        Node temp = top;
        top = temp.next;
        temp.next = null;
        return true;
    }

    int peek() {
        if (top == null)
            return -1;
        return top.data;
    }

    boolean isEmpty() {
        if (top == null)
            return true;
        return false;
    }

}

Prev Next

Comments