Skip to content

Commit

Permalink
Merge pull request #1 from Gargee07/Branch-for-Stack-using-two-queues…
Browse files Browse the repository at this point in the history
…-Code

Solution to Issue Mozilla-Campus-Club-Cummins#56 Stack using two queues
  • Loading branch information
Gargee07 authored Oct 26, 2023
2 parents 07a4557 + eb40914 commit 32dbe04
Showing 1 changed file with 94 additions and 0 deletions.
94 changes: 94 additions & 0 deletions Stack_Using_Queues.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Implementation of Stack using two Queues
*/
package stackImplementation;
import java.util.*;


class Stack{ // Stack class where all methods of stack are created
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
int size;

Stack(){
size=0;
}

//using Push Operation costly approach
void push(int element) {
size++;
q2.add(element); //adding recently entered element to q2

while (!q1.isEmpty()) {
q2.add(q1.peek()); // moving all the elements of q1 to q2
q1.remove();
}

Queue<Integer> temp = q1;
q1 = q2; //swapping the queues
q2 = temp;
}


int pop() { // returns and remove the recently entered element
if (q1.isEmpty()) {
return -1; } //returns -1 for empty queue
else{
size--;
return q1.remove();
}
}


int top() { // returns the recently entered element
if (q1.isEmpty())
return -1;
return q1.peek();
}


int size() { // returns the size of stack
return size;
}
}

public class Stack_Using_Queues {

public static void main(String[] args) {
Scanner input=new Scanner (System.in);
Stack stack=new Stack(); //Instantiating Stack class
char m;int choice;
do {


System.out.println("Enter the choice from the menu");
System.out.println(" 1.Push element\n 2.Pop element"); //menu
choice=input.nextInt();
switch(choice) {
case 1:{
System.out.println("Enter number:");
int x=input.nextInt();
stack.push(x);
break;
}
case 2: {
System.out.println(stack.pop());
break;
}

default: {
System.out.println("Enter valid input");
}
}
System.out.println("Press 'Y' to continue to menu or press 'N' to exit");
m=input.next().charAt(0);

if(m=='n'|| m=='N') {
System.out.println("The program has exited successfully");
System.exit(0);}
}while(m=='y' || m=='Y');

input.close();
}

}

0 comments on commit 32dbe04

Please sign in to comment.