1

我设置了以下代码:

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) 但只返回第一个对象地址

4

2 回答 2

4

我认为你的pop()函数应该返回的是endEl.object.

于 2013-05-06T21:31:10.243 回答
1

你的代码太啰嗦了。堆栈是一种可以有效地推送弹出元素的数据结构。但是您的代码必须为这两个操作遍历整个堆栈(即以O(n)而不是O(1)时间运行。)。

预先添加到您的列表比添加更有效。

高效推送示例:

public void push(Object o) {
    firstItem = new List(o, firstItem);
    size++;
}
于 2013-05-06T21:29:21.897 回答