【发布时间】:2016-01-22 15:14:56
【问题描述】:
我无法理解如何将从堆栈中弹出的对象存储为变量。
例如:
堆栈由数字组成: 3 , 4 , 5 [3 在堆栈顶部]
**我将整数推入名为 postfix 的 char[] 数组中。
***当我 pop() 时,我希望能够将其设置为变量 (x)。所以 x = 3
**** 弹出后 : 4 , 5
*****然后当我再次弹出()时,我想将其设置为另一个变量(y)。 y = 4
*****我想将它们设置为变量的原因是因为我打算使用它们来评估一个等式,例如:x + y,x - y 等,并将两者的结果返回给栈顶。对不起,我真的迷路了。
通用节点类:
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;
}
通用 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);
}
***********************************************************
界面:
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
【问题讨论】:
-
看来你需要一个数组来存储所有弹出的元素。
-
那么一个数组用来保存推入的整数,一个用来保存弹出的整数?
-
不,我不建议你,但它只是你需要执行 + , - 对于两个弹出的元素然后操作是可能的,否则我担心你会再次需要一个数据结构