Question: Question 3 : Write a method in the Demo class ( name it reverseString ) , call the method from the main ( ) and

Question 3:
Write a method in the Demo class (name it reverseString), call the method from the main() and pass a string to it. This method will do the following:
Receives a string (sentence, not just one word).
Stores the received string in an linkedlist-based stack
Prints the sentence in reverse.
Example:
Call statement: reverseString("Testing my reverseString method");
output: dohtem gnirtSesrever ym gnitseT
**Demo class below**
public class LinkedListStackDemo {
public static void main(String[] args){
LinkedStack LS = new LinkedStack();
LS.push("Test");
LS.push("Testing");
LS.push("Tested");
System.out.println(LS);
int numEl = LS.numValues();
System.out.println("Number of elements stored in stack: "+ numEl);
}
//reverseString class
public static void reverseString(String sentence){
LinkedStack st = new LinkedStack();
}
**LinkedStack class below**
public class LinkedStack {
private Node top = null;
public boolean empty(){
return top == null;
}
public void push(String s){
top = new Node(s, top);
}
public String pop(){
String retValue;
if (empty()){
throw new IllegalStateException();
} else {
retValue = top.element;
top = top.next;
return retValue;
}
}
public String peek(){
if (empty()){
throw new IllegalStateException();
} else {
return top.element;
}
}
public int numValues(){
int count =0;
Node curr = top;
while (curr != null){
count++;
curr = curr.next;
}
return count;
}
public String toString(){
Node ref = top;
String toPrint ="";
while (ref != null){
toPrint +=","+ ref.element;
ref = ref.next;
}
return "The elements in the stack reversed are: "+ toPrint;
}
// Node class used for linked list
private class Node {
String element;
Node next;
Node(String e, Node n){
element = e;
next = n;
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!