2012-01-28 112 views
0

我的代碼中出現「分段錯誤」。哪裏不對?提前致謝。這是一個使用鏈表的堆棧。堆棧使用鏈表

#include <iostream> 
//stack using linked list 
class LinkedList { 
public: 
    LinkedList() : head(0), tail(0) {} 
    ~LinkedList() { 
    while (!empty()) pop(); 
    delete head; 
    } 
    void pop() { 
    node* temp; 
    temp = head; 
    for (; temp->next_ != tail; temp = temp->next_) { 
     tail = temp; 
    } 
    delete temp; 
    tail->next_ = 0; 
    } //removes, but does not return, the top element 
    int top() { 
    return tail->value_; 
    } //returns, but does not remove, the top element 
    bool empty() { 
    return head == 0; 
    } 
    void push(const int& value) { 
    node* element = new node(value); 
    if (empty()) { 
     head = tail = element; 
    } else { 
     tail->next_ = element; 
     tail = element; 
    } 
    } //place a new top element 
private: 
    class node { 
    public: 
    node(const int& input) : value_(input), next_(0) {}; 
    int value_; //store value 
    node* next_; //link to the next element 
    }; 
    node* head; 
    node* tail; 
}; 
int main() { 
    LinkedList list; 
    list.push(1); 
    list.push(2); 
    list.push(3); 
    list.pop(); 
    std::cout << list.top() << std::endl; 
    return 0; 
} 
+1

您是否嘗試用'gdb'調試您的代碼? – 2012-01-28 07:40:16

+3

您是否發現您應該至少告訴您的代碼崩潰? – 2012-01-28 07:40:33

回答

2

這部分看起來不正確

for (; temp->next_ != tail; temp = temp->next_) { 
    tail = temp; 
} 

,因爲一旦你設置tail是一樣temptemp->next != tail永遠是正確的。

+0

它確實給了我正確的答案。但它說「雙重免費或腐敗」 – ihm 2012-01-28 14:10:47

1
for (; temp->next_ != tail; temp = temp->next_) { 
     tail = temp; 
} 

條件應該已經

temp->next_ != 0 
0

我認爲這個問題是:

for (; temp->next_ != tail; temp = temp->next_) { 
    tail = temp; 
} 
delete temp; 
tail->next_ = 0; 

尾=溫度應該是你發現導致尾臨時後(即外for循環)。 另外,temp =不是尾巴,而是尾巴之前的尾巴。所以,很可能你需要:

for (; temp->next_ != tail; temp = temp->next_) {} 
delete tail; 
tail = temp; 
tail->next_ = 0; 
1

這種方法

void pop() { 
    node* temp; 
    temp = head; 
    for (; temp->next_ != tail; temp = temp->next_) { 
     tail = temp; 
    } 
    delete temp; 
    tail->next_ = 0; 
    } //removes, but does not return, the top element 

必須是這樣的:

void pop() { 
    if(head == tail) 
    { 
     delete head; 
     head = 0; 
    } 
    else 
    { 
     node* temp; 
     temp = head; 
     for (; temp->next_ != tail; temp = temp->next_) { 
     } 
     delete tail; 
     temp->next_ = 0; 
     tail = temp; 
    } 
    } //removes, but does not return, the top element 
0

析構函數看起來越野車對我說:你把 「啪」,直到空()返回true,當head是空指針時發生。但是,然後你不能在while循環結束後調用頭部刪除...

我不知道這是否是問題,但我會檢查它。

另一個不起眼的提示:你沒有告訴我們seg故障發生在哪裏......如果你用gdb運行你的代碼(或者你只是在你的代碼中放了很多「cout」),你可以檢測到會導致你的問題。