Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create StackUsingQueue.java #86

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions JAVA/ReverseStringUsingStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.Stack;

public class ReverseStringUsingStack {
public static String reverseString(String input) {
Stack<Character> stack = new Stack<>();

// Push each character of the input string onto the stack
for (char c : input.toCharArray()) {
stack.push(c);
}

// Pop the characters from the stack to build the reversed string
StringBuilder reversedString = new StringBuilder();
while (!stack.isEmpty()) {
reversedString.append(stack.pop());
}

return reversedString.toString();
}

public static void main(String[] args) {
String input = "Hello, World!";
String reversed = reverseString(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversed);
}
}
40 changes: 40 additions & 0 deletions JAVA/StackUsingQueue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.LinkedList;
import java.util.Queue;

public class StackUsingQueue {
private Queue<Integer> queue1;
private Queue<Integer> queue2;

public StackUsingQueue() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}

public void push(int element) {
queue2.offer(element);
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}

public int pop() {
if (queue1.isEmpty()) {
return -1; // Stack is empty
}
return queue1.poll();
}

public int top() {
if (queue1.isEmpty()) {
return -1; // Stack is empty
}
return queue1.peek();
}

public boolean isEmpty() {
return queue1.isEmpty() && queue2.isEmpty();
}
}