制作链表:获取分段错误

时间:2016-05-24 23:28:54

标签: c++

我正在练习如何在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);

 }





 }

1 个答案:

答案 0 :(得分:0)

我认为你在添加节点时遇到了错误。

我看到的问题是,在第一次插入后,你已经正确分配了一个头部,但尾部没有做任何事情。在下一个插入中,因为你的头是有效的,你进入'make second node'代码块,在这里你试图去引用尚未初始化的尾部成员。