Skip to content

Commit

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

Solution to Issue #56 Stack using two queues
  • Loading branch information
ManasiGDeshmukh authored Oct 31, 2023
2 parents df9c7d6 + b74b2bd commit a3ce59e
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Implementation of Stack using two Queue
*/
package stackUsingQueues;
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>();

//using Push Operation costly approach
void push(int element) {

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{
return q1.remove();
}
}
}
public class Main { //Main class

public static void main(String[] args) {
Scanner input=new Scanner (System.in);
Stack stack=new Stack(); //Instantiating Stack class
stack.push(2);
stack.push(3);
System.out.print(stack.pop()+" ");
stack.push(4);
System.out.print(stack.pop()+" ");


input.close();
}
}
53 changes: 53 additions & 0 deletions Stack_Using_Queues.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Implementation of Stack using two Queue
*/
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>();

//using Push Operation costly approach
void push(int element) {

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{
return q1.remove();
}
}
}

public class Stack_Using_Queues {

public static void main(String[] args) {
Scanner input=new Scanner (System.in);
Stack stack=new Stack(); //Instantiating Stack class
stack.push(2);
stack.push(3);
System.out.print(stack.pop()+" ");
stack.push(4);
System.out.print(stack.pop()+" ");



input.close();
}

}

0 comments on commit a3ce59e

Please sign in to comment.