Skip to content

Commit

Permalink
Merge pull request HarshCasper#2311 from ritvij14/stack-queue
Browse files Browse the repository at this point in the history
added implementation of stack using Queue in Java
  • Loading branch information
iamrajiv authored Mar 9, 2021
2 parents 8862db8 + f3b4f24 commit a6442c3
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions Java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ _add list here_
- [Sparse Matrix](ds/SparseMatrix.java)
- [Stack ~ Linked List Implementation](ds/Stack.java)
- [Stack](ds/Stackll.java) Implementation-of-queue-using-stack
- [Implementation of Stack using Queue](ds/StackUsingQueue.java)
- [Tree Traversal(preorder traversal)](ds/preOrderTraversal.java)
- [Tree Traversal(postorder traversal)](ds/postorder_Traversal.java)
- [Priority Queue](ds/PriorityQueueEg.java)
Expand Down
98 changes: 98 additions & 0 deletions Java/ds/StackUsingQueue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* Java Program to implement a stack using two queues
by making the push operation costly*/

import java.util.*;

public class StackUsingQueue {
static class Stack {
// the 2 queues
Queue<Integer> qu1 = new LinkedList<>();
Queue<Integer> qu2 = new LinkedList<>();

// storing current size
int currentSize;

Stack() {
currentSize = 0;
}

void push(int num) {
currentSize++;

// first, push num into an empty qu2
qu2.add(num);

// now we push the other elements from qu1 to qu2
while (!qu1.isEmpty()) {
qu2.add(qu1.peek());
qu1.remove();
}
}

void pop() {
if (qu2.isEmpty()) {
return;
}

// remove element and reduce size if qu2 not empty
qu2.remove();
currentSize--;
}

int top() {
if (qu2.isEmpty()) {
return -1;
}

// return the top element
return qu2.peek();
}

int size() {
return currentSize;
}
}

public static void main(String[] args) {
Stack stack = new Stack();

Scanner sc = new Scanner(System.in);
System.out.println("Enter size:");
int size = sc.nextInt();
System.out.println("Enter the numbers:");
for (int i = 0; i < size; i++) {
stack.push(sc.nextInt());
}
sc.close();

System.out.println("Current Size:" + stack.size());
for (int i = size; i > 0; i--) {
System.out.println(stack.top());
stack.pop();
}
System.out.println("Current Size:" + stack.size());
}
}

/**
* Sample input/output:
*
* Enter size:
* 5
* Enter the numbers:
* 5
* 4
* 3
* 2
* 1
* Current Size:5
* 5
* 4
* 3
* 2
* 1
* Current Size:0
*
* Time complexity: O(n) for push, O(1) for pop
* Space complexity: O(n)
*/

0 comments on commit a6442c3

Please sign in to comment.