我的代码中出现“分段错误”。怎么了?提前致谢。 p.s它是一个使用链表的堆栈。
#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;
}
答案 0 :(得分:2)
这部分看起来不正确
for ( ; temp->next_ != tail; temp = temp->next_) {
tail = temp;
}
因为一旦您将tail
设置为与temp
相同,temp->next != tail
将始终为真。
答案 1 :(得分:1)
for ( ; temp->next_ != tail; temp = temp->next_) {
tail = temp;
}
条件应该是
temp->next_ != 0
答案 2 :(得分: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
答案 3 :(得分:0)
我认为问题是:
for ( ; temp->next_ != tail; temp = temp->next_) {
tail = temp;
}
delete temp;
tail->next_ = 0;
tail = temp应该在你找到导致尾部的温度之后(即在for循环之外)。 而且,temp =不是尾巴而是尾巴之前的尾巴。所以你可能需要:
for ( ; temp->next_ != tail; temp = temp->next_) {}
delete tail;
tail = temp;
tail->next_ = 0;
答案 4 :(得分:0)
析构函数对我来说是错误的:你保持“弹出”直到empty()返回true,这在head为空指针时发生。但是,在while循环结束后你不能在头上调用delete ...
我不知道这是不是问题,但我会检查一下。
另一个不起眼的提示:你没有告诉我们seg故障发生在哪里......如果你用gdb运行你的代码(或者你只是在你的代码中放了很多“cout”),你可以检测到这一行这会给你带来麻烦。