The code is giving two errors, can someone please sort this out. public class St
ID: 3908722 • Letter: T
Question
The code is giving two errors, can someone please sort this out.
public class StringStack {
private Node top;
public StringStack(){
top=null;
}
public boolean isEmpty() {
if(this.head==null){
return true;
}
else{
return false;
}
}
public String pop throws StackEmptyException() {
if(isEmpty()==false){
String popped;
Node oldTop;
oldTop=top;
popped=top.getData();
top=top.getNext();
oldTop.setNext(null);
return popped;
}else{
throw new StackEmptyException("The stack is empty! popping disabled...");
}
}
public String peek() throws StackEmptyException {
if(isEmpty()==false){
return top.getData();
}else{
throw new StackEmptyException("The stack is empty! peeking disabled...");
}
}
public void push(String item) {
if(isEmpty()==true){
Node temp = new Node(item);
top=temp;
}else{
Node prevTop;
prev=top;
Node temp= new Node(item);
temp.setNext(prevTop);
top= temp;
}
}
public void popAll() {
top= null;
}
public String toString(){
String str = "Top: ";
Node curr= top;
while (curr!=null){
str +=curr.getData()+ " ";
curr=curr.getNext();
}
}
}
Explanation / Answer
If you have any doubts, please give me comment...
public class StringStack{
private Node top;
public StringStack() {
top = null;
}
public boolean isEmpty() {
if (this.head == null) {
return true;
} else {
return false;
}
}
public String pop() throws StackEmptyException {
if (isEmpty() == false) {
String popped;
Node oldTop;
oldTop = top;
popped = top.getData();
top = top.getNext();
oldTop.setNext(null);
return popped;
} else {
throw new StackEmptyException("The stack is empty! popping disabled...");
}
}
public String peek() throws StackEmptyException {
if (isEmpty() == false) {
return top.getData();
} else {
throw new StackEmptyException("The stack is empty! peeking disabled...");
}
}
public void push(String item) {
if (isEmpty() == true) {
Node temp = new Node(item);
top = temp;
} else {
Node prevTop;
prev = top;
Node temp = new Node(item);
temp.setNext(prevTop);
top = temp;
}
}
public void popAll() {
top = null;
}
public String toString() {
String str = "Top: ";
Node curr = top;
while (curr != null) {
str += curr.getData() + " ";
curr = curr.getNext();
}
}
}