Stacks and Queues

Stacks and Queues

A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. It can be visualized as a collection of elements arranged in a vertical structure, where elements are inserted and removed from the top, known as the "top of the stack."

Implementation

  • isEmpty()

  • push()

  • pop()

  • peek()

    static class Stack {
        private ArrayList<Integer> list;

        // Constructor to initialize the ArrayList
        public Stack() {
            list = new ArrayList<>();
        }
}

isEmpty()

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

pop()

  public int pop() {
            if (isEmpty()) {
                return -1; // Return a sentinel value or throw an exception to indicate underflow
            }
            return list.remove(list.size() - 1);
        }

push()

public void push(int data) {
            list.add(data);
        }

peek()

 public int peek() {
            if (isEmpty()) {
                return -1; // Return a sentinel value or throw an exception to indicate underflow
            }
            return list.get(list.size() - 1);
        }

Queue

A queue is another fundamental data structure that follows the First In, First Out (FIFO) principle. It can be visualized as a line of elements, where new elements are added at the rear (enqueue) and existing elements are removed from the front (dequeue).

 static class Queue {
        private ArrayList<Integer> list;


        public Queue() {
            list = new ArrayList<>();
        }
}

isEmpty()

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

enqueue()

 public void enqueue(int data) {
            list.add(data);
        }

dequeue()

 public int dequeue() {
            if (isEmpty()) {
                return -1; 
            }
            return list.remove(0);
        }

peek()

 public int peek() {
            if (isEmpty()) {
                return -1; 
            }
            return list.get(0);
        }

Did you find this article valuable?

Support Thirumalai by becoming a sponsor. Any amount is appreciated!