2011-04-04 84 views
0

嘿。我被分配到使用雙鏈表執行堆棧,並且遇到了問題。我無法鏈接到以前的元素(雖然我沒有使用一個鏈接的問題)。使用雙鏈表的堆棧

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

聽起來有點像家庭作業。如果它是作業標籤它。否則:爲什麼你在java中手動實現鏈表?改用ArrayList。 – Heisenbug 2011-04-04 10:51:15

+0

我會說空引用異常... – forsvarir 2011-04-04 10:59:01

+0

這是沒有辦法檢索頂部元素。 pop()應該返回數據。 – Manoj 2011-04-04 10:59:59

回答

1

//oldElement.previous = topElement; // < -----問題在這裏

正如已經指出的那樣:如果oldElement爲空,您將得到一個NullPointerException。檢查之前爲空,如if(oldElement != null) { oldElement.previous = topElement; }

另請注意,Top()方法不適用於空堆棧,它會在第一行topElement.data...中引發NPE。

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)]