使用双链表进行堆叠

时间:2011-04-04 10:47:29

标签: java dynamic stack linked-list

嘿。我被分配使用双链表做堆栈,我遇到了问题。我无法链接到上一个元素(虽然我使用一个链接没有问题)。

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();
    }

}

2 个答案:

答案 0 :(得分:1)

  

// oldElement.previous = topElement; //&lt; -----问题在这里

正如已经指出的那样:如果oldElement为null,则会出现NullPointerException。之前检查为null,例如if(oldElement != null) { oldElement.previous = topElement; }

另请注意,Top()方法不适用于空堆栈,它会在第一行topElement.data...中抛出NPE。

答案 1 :(得分:0)

看看不同的情况:

{Stack} //Top of stack is the leftmost node

[Node(Next|Prev)]

案例:#1“空堆案例”

{null}

Push:

[Node1(null|null)]

案例:#2“正常情况”

{[Node1(null|null)]}

Push:

[Node2(Node1|null)]

Change:

[Node1(null|null)] -> [Node1(null|Node2)]

查看案例:#3我们看到它类似于案例#2,无需实施

{[Node2(Node1|null)],[Node1(null|Node2)]}

Push:

[Node3(Node2|null)]

Change:

[Node2(Node1|null)] -> [Node2(Node1|Node3)]