-3
我正在練習如何在C++中創建鏈接列表,代碼如下。我是否分配錯誤?我不確定它是否是我的構造函數,用於導致錯誤的節點或列表,但我不斷收到分段錯誤。我是一名初學者,我真的很想理解內存分配。製作鏈表:獲取分段錯誤
main.cpp中:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "list.h"
using namespace std;
int main(void)
{
int option;
list *linked;
linked = new list;
while(1)
{
// menu
cout<<"********************************************"<<endl;
cout<<" what option would you like to use "<<endl;
cout<<" 1.add a node"<<endl;
cout<<" 2.show list"<<endl;
cout<<" 3.delete node"<<endl;
cout<<"********************************************"<<endl;
cin>>option;
//switch for option
switch(option)
{
case 1 :
cout<<"you picked add a node"<<endl;
(*linked).add_node();
break;
case 2 :
cout<<"you picked show list"<<endl;
break;
case 3 :
cout<<"you picked delete node"<<endl;
break;
default:
cout<<"thats not a valid option"<<endl;
break;
}
}
return 0;
}
list.h:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
using namespace std;
class node
{
private:
node *next;
node *prev;
string note;
public:
// constructor
node();
//gets
node* get_next(void)
{return next;}
node* get_prev(void)
{return prev;}
// setts
void set_next(node* x)
{next=x;}
void set_prev(node* x)
{prev=x;}
};
class list
{
private:
node *head, *current, *tail;
public:
//constructor
list();
void add_node(void);
};
node::node(void)
{
string x;
cout<<"hi"<<endl;
//set front and back null
next=NULL;
prev=NULL;
//write the note
cout<<" what note would you like to write in the node"<<endl;
cin>>x;
note=x;
}
list::list(void){
//start the list pointing to null
head = tail = NULL;
}
void list::add_node(void)
{
//make first node
if(head=0){
head = new node;
cout<<"1"<<endl;
}
//make 2nd node
else if((*head).get_next()==0){
cout<<"2"<<endl;
node* temp;// buffer
temp= new node;
(*head).set_next(temp);
(*head).set_prev(temp);
(*tail).set_next(head);
(*tail).set_prev(head);
}
}
'如果(head = 0)'總是返回'true' – Wentao
@Rahn實際上它總是假的,它會另外將'head'設置爲NULL。 – immibis
除了實際指出,缺乏一致的縮進使這個代碼幾乎不可讀。 –