我设置了以下代码:
public class ListStack implements Stack {
private class List {
List next;
Object object;
public List(Object o, List n) {
object = o;
next = n;
}
}
private List firstItem;
private int size;
public ListStack() {
firstItem = new List(null, null);
size = 0;
}
public List getEnd() {
List endEl = firstItem;
while (endEl.next != null) {
endEl = endEl.next;
}
return endEl;
}
public boolean push(Object o) {
List e1 = new List(o, null);
this.getEnd().next = e1;
size++;
return true;
}
public Object pop() {
if (this.firstItem.next == null) {
return null;
} else {
List endEl;
List tempEl;
endEl = this.getEnd();
tempEl = firstItem;
while (tempEl.next != endEl) {
tempEl = tempEl.next;
}
tempEl.next = null;
size--;
return tempEl.object;
}
}
public int size() {
return size;
}
public static void main(String[] args) {
Stack s = new ListStack();
Object test = new Object();
Object test2 = new Object();
System.out.println("pushing Object test to List: " + s.push(test));
System.out.println("pushing Object test2 to List: " + s.push(test2));
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
System.out.println("popping Object from List: " + s.pop());
}
}
和这个:
public interface Stack {
public int size();
public boolean push(Object o);
public Object pop();
}
但它只给了我第一个对象和两次“null”,但它应该给我两个对象:(我的错误在哪里?它要求最后一个项目并将其返回 (.object) 但只返回第一个对象地址