***** LLStack class ***** public class LLStack { private java.util.LinkedList li
ID: 3730767 • Letter: #
Question
***** LLStack class *****
public class LLStack {
private java.util.LinkedList list = new java.util.LinkedList();
public LLStack() {
}
public void clear() {
list.clear();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Object topEl() {
if (isEmpty())
throw new java.util.EmptyStackException();
return list.getLast();
}
public Object pop() {
if (isEmpty())
throw new java.util.EmptyStackException();
return list.removeLast();
}
public void push(Object el) {
list.add(el);
}
public String toString() {
return list.toString();
}
}
*** End of LLStack class ***
***** Queue Class ******
public class Queue {
private java.util.LinkedList list = new java.util.LinkedList();
public Queue() {
}
public void clear() {
list.clear();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Object firstEl() {
return list.getFirst();
}
public Object dequeue() {
return list.removeFirst();
}
public void enqueue(Object el) {
list.add(el);
}
public String toString() {
return list.toString();
}
}
**** End of Queue Class ****
**** Stack class ****
public class Stack {
private java.util.ArrayList pool = new java.util.ArrayList();
public Stack() {
}
public Stack(int n) {
pool.ensureCapacity(n);
}
public void clear() {
pool.clear();
}
public boolean isEmpty() {
return pool.isEmpty();
}
public Object topEl() {
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.get(pool.size()-1);
}
public Object pop() {
if (isEmpty())
throw new java.util.EmptyStackException();
return pool.remove(pool.size()-1);
}
public void push(Object el) {
pool.add(el);
}
public String toString() {
return pool.toString();
}
}
***** End of stack class *****
*** Stack Test Class ****
import java.util.*;
public class StacksTest {
public static void main(String[] args) {
Stack s = new Stack();
s.push(new Integer(3));
s.push(new Integer(5));
s.push(new String("hi"));
while(!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
s.clear(); //Empty the contents of the stack
System.out.println(" Here's how I reverse a string: ");
Scanner k = new Scanner(System.in);
System.out.print("Enter a string> ");
String input = k.nextLine();
for(int i = 0; i < input.length(); i++)
s.push(input.charAt(i) + "");
System.out.println("The reversed string is: ");
while(!s.isEmpty()) {
System.out.print(s.pop());
}
System.out.println();
}
}
2. (15 points) Write a program reverseStack to reverse the order of elements on stack s using a Queue. Develop a test method that checks how your program runs when given a stack of Integers.Explanation / Answer
Please find my implementation.
public void reverseStack() {
Queue queue = new Queue();
while(!isEmpty()) {
queue.enqueue(pop());
}
while(queue.isEmpty()) {
this.push(queue.dequeue());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.