#include<iostream>
using namespace std;
class list
{
public:
list();
bool insertHead(int n);
private:
struct node
{
int item;
node *next;
};
node* head;
};
list::list()
{
head = NULL;
head -> item = 0;
head -> next = NULL;
}
bool list::insertHead(int n)
{
node* tempptr = new node;
tempptr->item = n;
tempptr->next = head;
head = tempptr;
return true;
}
int main()
{
list test1;
test1.insertHead(4);
return 0;
}
此代碼在運行時編譯好但不幸運行段錯誤。我試圖在insertHead函數的末尾添加刪除tempptr,但無濟於事。在內存分配方面我非常糟糕,我知道分段錯誤與運行時內存分配有關。有誰能夠幫助我?我只是使用insertHead將整數插入鏈表的前面。有人可以幫我嗎?謝謝!我將實現和其他文件組合在一起,因此更易於閱讀......我想。謝謝分段錯誤11鏈接列表節點結構
爲什麼'delete'會解決分段錯誤?另外,你是否嘗試在調試器中運行你的代碼? – 2013-07-18 07:00:41
它在哪裏段錯? – chris
在'list :: list'中,您設置了'head = NULL',然後嘗試對其進行解引用。你期望如何工作? – Barmar