我的代碼中出現「分段錯誤」。哪裏不對?提前致謝。這是一個使用鏈表的堆棧。堆棧使用鏈表
#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;
}
您是否嘗試用'gdb'調試您的代碼? – 2012-01-28 07:40:16
您是否發現您應該至少告訴您的代碼崩潰? – 2012-01-28 07:40:33