Site icon

Create/ implement stack using single linked list in java (generics /example)

Program – Create or implement stack using single linked list in java

1.) Stack class:

package org.learn;

import java.util.EmptyStackException;
import java.util.LinkedList;

public class Stack<T> {

    private LinkedList<T> stack;

    public Stack() {
        stack = new LinkedList();
    }

    public void push(T element) {
        stack.addFirst(element);
    }

    public T pop() {

        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return stack.removeFirst();
    }

    public boolean isEmpty() {
        if (stack.size() == 0) {
            return true;
        }
        return false;
    }

    public int size() {
        return stack.size();
    }
}

2.) StackClient:

package org.learn;

public class StackClient {

    public static void main(String[] args) {

        System.out.println("1. Stack of integers");
        stackOfIntegers();

        System.out.println("\n2. Stack of Strings");
        stackOfIStrings();
    }

    private static void stackOfIStrings() {

        Stack<String> stack = new Stack();
        stack.push("Five");
        stack.push("Four");
        stack.push("Three");
        stack.push("Two");
        stack.push("One");

        System.out.println("1.1 Size of stack after push operations: " + stack.size());

        System.out.printf("1.2. Pop elements from stack : ");
        while (!stack.isEmpty()) {
            System.out.printf(" %s", stack.pop());
        }

        System.out.println("\n1.3. Size of stack after pop operations : " + stack.size());
    }

    private static void stackOfIntegers() {

        Stack<Integer> stack = new Stack();
        stack.push(5);
        stack.push(4);
        stack.push(3);
        stack.push(2);
        stack.push(1);

        System.out.println("2.1. Size of stack after push operations: " + stack.size());
        System.out.printf("2.2. Pop elements from stack : ");

        while (!stack.isEmpty()) {
            System.out.printf(" %d", stack.pop());
        }

        System.out.println("\n3.3 Size of stack after pop operations : " + stack.size());
    }
}

Output – Create or implement stack using single linked list in java

1. Stack of integers
2.1. Size of stack after push operations: 5
2.2. Pop elements from stack :  1 2 3 4 5
3.3 Size of stack after pop operations : 0

2. Stack of Strings
1.1 Size of stack after push operations: 5
1.2. Pop elements from stack :  One Two Three Four Five
1.3. Size of stack after pop operations : 0
Exit mobile version