Pages

Saturday, October 18, 2025

Stack using Deque in java

 import java.util.*;


// Deque: Double-ended queue, allows insertion & removal from both ends , rear and front end.

// Dequeue(verb, action, method): To remove an element from the front of a queue.


public class Main

{

    static class Stack {

        Deque<Integer> deque = new LinkedList<>();

        

        

        public void push(int data) {

            deque.addLast(data);

        }

        

        

        public int pop() {

            return deque.removeLast();

        }

        

        public int peek() {

            return deque.getLast();

        }

    

    }

    

public static void main(String[] args) {

Stack s = new Stack();

s.push(1);

s.push(2);

s.push(3);

System.out.println("peek = " + s.peek());

    System.out.println(s.pop()); // 3 2 1 -> 3

    System.out.println(s.pop()); // 2 1 -> 2

    System.out.println(s.pop()); // 1 -> 1

}

}

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...