Stack is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects.
A stack, under the hood, is an ordered list in which insertion and deletion are done only at the top. The last element inserted is the first one to be deleted. Hence, it is called the Last in First out (LIFO) or First in Last out (FILO) list.
A pile of plates in a cafeteria is a good example of a stack. The plates are added to the stack as they are cleaned and they are placed on the top. When a plate, is required it is taken from the top of the stack. The first plate placed on the stack is the last one to be used.
Special names are given to the two changes that can be made to a stack. When an element is inserted in a stack, the concept is called push, and when an element is removed from the stack, the concept is called pop. Trying to pop out an empty stack is called underflow and trying to push an element in a full stack is called overflow.
push()
function is used to insert new elements into the Stack and pop()
function is used to remove an element from the stack. Both insertion and removal are allowed at only one end of Stack called Top.@Data @NoArgsConstructor public class MyStack<E> { private LinkedList<E> list = new LinkedList<>(); public E push(E item) { list.addFirst(item); return item; } public E pop() { if (list.size() <= 0) { throw new EmptyStackException(); } return list.remove(); } public int getSize() { return list.size(); } public E peek() { if (list.size() <= 0) { throw new EmptyStackException(); } return list.getFirst(); } public void print() { int size = getSize(); int count = 1; if (count >= size) { return; } E item = list.getFirst(); while (item != null) { System.out.println(item.toString()); if (count >= size) { break; } item = list.get(count); count++; } } }