Sunday, 13 November 2022

Implement stack data structure using List

Stack is a linear data structure that works on the principle known as LIFO (Last In First Out). Element inserted at the last is removed first from the stack.

 

There are two basic operations in stack.

a.   push(): Add element to the stack

b.   pop(): Remove an element from the stack. Element inserted recently is removed from the stack.

 

Find the below working application.


Stack.java

package com.sample.app.collections;

import java.util.ArrayList;

public class Stack<T> {

	private final ArrayList<T> stack;

	public Stack() {
		stack = new ArrayList<T>();
	}

	public void push(T obj) {
		stack.add(obj);
	}

	public T pop() {
		return stack.remove(stack.size() - 1);
	}

	public boolean isEmpty() {
		return stack.isEmpty();
	}

	public void clear() {
		stack.clear();
	}

	@Override
	public String toString() {
		return stack +"";
	}

}

StackDemo.java

package com.sample.app.collections;

public class StackDemo {

	public static void main(String[] args) {
		Stack<Integer> myStack = new Stack<>();
		myStack.push(10);
		myStack.push(20);
		myStack.push(30);
		myStack.push(40);

		System.out.println(myStack);

		System.out.println("Popping one element from the stack");
		myStack.pop();

		System.out.println(myStack);

		System.out.println("\nis stack empty : " + myStack.isEmpty());

		System.out.println("\nClear all the elements from the stack");
		myStack.clear();
		System.out.println("is stack empty : " + myStack.isEmpty());
	}

}

Output

[10, 20, 30, 40]
Popping one element from the stack
[10, 20, 30]

is stack empty : false

Clear all the elements from the stack
is stack empty : true



You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an array to set in Java

Get the string representation of an Iterable

Convert an Iterable to List in Java

Convert an Iterable to a Set in Java

Get the last element from a collection in Java

No comments:

Post a Comment