I'm having trouble understanding how to store objects I pop from a stack as variables.
For example:
A stack consists of numbers: 3 , 4 , 5 [3 being on the top of the stack]
**I push my integers into my char[] array called postfix.
***When I pop() I want to be able to set it to a variable (x). so x = 3
**** After pop : 4 , 5
*****Then when I pop() again I want to set that as another variable(y). y = 4
*****The reason why I want to set them as variables is because I plan on using them to evaluate an equation like : x + y , x - y, etc. and return the result of the two on to the top of the stack. I'm sorry but I'm really lost.
Generic Node Class:
public class Node<T> {
// data fields (reference variables)
// data stores an object of any class
private T data;
// next points to the next node
private Node<T> next;
/**
* Constructor - Used To Create Each Object & Initialize DAta Fields.
*
* @param data2
* initializes the data reference variable.
* @param next2
* initializes the next reference variable..
*/
public Node(T data2, Node<T> next2) {
data = data2;
next = next2;
}
public T getData() {
return data;
}
public Node<T> getNext() {
return next;
}
public void setData(T data2) {
data = data2;
}
public void setNext(Node<T> next2) {
next = next2;
}
Generic LinkedStack:
import java.util.EmptyStackException;
public class LinkedStack<T> implements StackInterface<T> {
private Node<T> top = null;
public LinkedStack() {
//data fields already initialized
}
public boolean empty() {
return top == null;
}
public T peek() throws EmptyStackException {
//check to see if empty
if(this.empty()){
throw new EmptyStackException();
}
return top.getData();
}
public T pop() {
if(this.empty()){
throw new EmptyStackException();
}
Node<T> node = top;
top = top.getNext();
return node.getData();
}
public void push(T item) {
top = new Node<T>(item, top);
}
***********************************************************
Interface:
import java.util.EmptyStackException;
public interface StackInterface<T>{
/**Tests if the stack is empty
* @return true/false if empty/not empty */
public boolean empty();
/**Looks at the object at the top of the stack
* without removing it from the stack.
* @return the address to the top item on the stack
* @exception EmptyStackException if the stack is empty*/
public T peek() throws EmptyStackException;
/**Removes the object at the top of stack
* and returns the address of this object
* @return the address to the top item on the stack
* @exception EmptyStackException if the stack is empty*/
public T pop() throws EmptyStackException;
/**Pushes an item onto the top of this stack
* @param item the item that is pushed on the stack */
public void push(T item);
}//end interface