嘿。我被分配到使用双链表执行堆栈,并且遇到了问题。我无法链接到以前的元素(虽然我没有使用一个链接的问题)。使用双链表的堆栈
class Node
{
Data data;
Node previous;
Node next;
}
class Data
{
int size;
double price;
boolean isOnOffer;
char sex;
String brand;
Data(int size, double price, boolean isOnOffer, char sex, String brand){
this.size = size;
this.price = price;
this.isOnOffer = isOnOffer;
this.sex = sex;
this.brand = brand;
}
}
class Stack
{
private static int sizeOfStack;
private static Node topElement;
public static boolean isEmpty() { return topElement == null; }
public static void Initialize() {
sizeOfStack = 0;
topElement = null;
}
public static void Push(Data x) {
Node oldElement = topElement;
topElement = new Node();
topElement.data = x;
topElement.next = oldElement;
topElement.previous = null;
//oldElement.previous = topElement; // <----- problem here
sizeOfStack++;
}
public static void Pop() {
if (!isEmpty()){
topElement = topElement.next; // delete first node
sizeOfStack--;
}
}
public static void Top() {
int size = topElement.data.size;
double price = topElement.data.price;
boolean isOnOffer = topElement.data.isOnOffer;
char sex = topElement.data.sex;
String brand = topElement.data.brand;
System.out.println(size + " " + price + " " + isOnOffer + " " + sex + " " + brand);
}
public static void Kill() { }
public static void Print() { }
public static void main(String[] args){
Push(new Data(37, 155, false, 'F', "Nike"));
Push(new Data(38, 140, true, 'F', "Reebok"));
Push(new Data(35, 160.99, false, 'F', "Converse"));
Push(new Data(35, 20.99, true, 'F', "Inkaras"));
Pop();
Pop();
Top();
}
}
听起来有点像家庭作业。如果它是作业标签它。否则:为什么你在java中手动实现链表?改用ArrayList。 – Heisenbug 2011-04-04 10:51:15
我会说空引用异常... – forsvarir 2011-04-04 10:59:01
这是没有办法检索顶部元素。 pop()应该返回数据。 – Manoj 2011-04-04 10:59:59