#408 Write method reverse Stack
Write method reverse Stack - Computer Science
ChemistryExplain daily providing Q&A content “#408 Write method reverse Stack" in Computer science, Ba computer science, Berkeley computer science, Computer science associate degree jobs
ChemistryExplain team has covered all Topics related to inorganic, organic, physical chemistry, and others So, Prepare these Chemistry Questions and Answers with Explanation Pdf.
For More Chegg Questions
Free Chegg Question
Write method reverse Stack(Stack s) that receives a stacks and reverse the order of its elements.
Free Chegg AnswerFor More Chemistry Notes and Helpful Content Subscribe Our YouTube Chanel - Chemistry Explain
Free Chegg Answer
Note: If you want string element other then integer then use replace Integer with String St
ReverseStack.java
import java.io.*;
import java.util.*;
class ReverseStack{
// We use < > to specify Parameter type
// this function will reverse the stack elements
public static <E> void reverseStack(Stack<E> stack) {
// if stack is empty the just return
if (stack.isEmpty()) {
return;
}
// Remove bottom element from stack
E bot = popBottom(stack);
// Reverse everything in stack
reverseStack(stack);
// Adding bottom element to top
stack.push(bot);
}
private static <E> E popBottom(Stack<E> stack) {
E top = stack.pop();
if (stack.isEmpty()) {
// If we removed the last element, return it
return top;
} else {
// Remove the last element from remaining
E bot = popBottom(stack);
// the element we removed is not the bottom element so add it back to the top of the stack
stack.push(top);
return bot; // return bottom
}
}
private static <E> void show(Stack<E> stack){
// create new iterator object
Iterator<E> iterator = stack.iterator();
while (iterator.hasNext()) {
E t = (E) iterator.next();
System.out.print(" "+t);
}
}
public static void main(String[] args) {
// Creating new stack object
Stack<Integer> stack = new Stack<>();
// pushing elements to the stack
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.push(10);
System.out.println("Before reverse");
System.out.println("----------
System.out.print("Stack Elements :");
show(stack); // This function will print the stack
ReverseStack reverseStack = new ReverseStack();
reverseStack.reverseStack(
System.out.println("\n\nAfter reverse");
System.out.println("----------
System.out.print("Stack Elements :");
show(stack); // This function will print the stack
}
}
Output
Labels: Chegg, Free Chegg Answer, Q&A Computer Science
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home