在c ++中删除链表节点

时间:2014-11-09 21:19:47

标签: c++ linked-list

我试图从c转换到c ++,我正在使用链接列表。我的列表构建正确(我认为),但我在删除列表时遇到问题。我不知道为什么。有一半时间我得到一个seg错误而另一半只在程序关闭之前经过一次删除循环。所以我有点迷茫。继承人的代码

功能:

#include <iostream>
#include <string>
#include "ll.h"

使用namespace std;

student::student()
{
cout<<"\nWhat is the name of the student? "<<flush;
cin>>this->name;
cout<<"What id of the student? "<<flush;
cin>>this->id;
cout<<"\n";
}



void student_list::new_student()
{
if(head==NULL)
    {
    cout<<"NULL"<<endl;
    head=new student;
    head->next=NULL;
    tail=head;
    }
else
    {
    tail->next=new student;
    tail=tail->next;
    tail->next=NULL;
    }
}

student_list::student_list()
{
head=tail=NULL;
}

void student_list::print()
 {
class student *walk; walk=head;
while(walk!=NULL)
    {
    cout<<walk->name<<": "<<walk->id<<endl;
    walk=walk->next;
    }
}

void student_list::deleter()
{
int x;
student *walk;
walk=head;
cout<<"test"<<endl;
while(walk!=NULL)
    {
    cout<<head->id<<endl;
    delete head;
    head->next=NULL;
    head=walk->next;
    walk=walk->next;
    }
}

主:

#include <iostream>
#include "ll.h"
#include <string>

using namespace std;

int main()
{
class student_list list;
int x, y, z;
cout<<"How many tests? "<<flush;
cin>>y;
for(x=0; x<y; x++)
    {
    list.new_student();
    }
list.print();
list.deleter();
cout<<"test1";
return 0;
}

标题:

    #ifndef __LLFUNC_H_INCLUDED__
#define __LLFUNC_H_INCLUDED__


#include <string>   

class student{
public:
    student *next;
    int id;
    std::string name;
public:
    student();
};  

class student_list{
private:
    student *head;
    student *tail;
public:
    student_list();
    void new_student();
    void print();
    void deleter();
};
#endif

3 个答案:

答案 0 :(得分:0)

问题是您在尝试迭代前设置walk->next=NULL,尝试存储&#39; next&#39;将它归零之前的指针并删除当前项。我还删除了walk,因为它完全没有必要,因为您已经在使用head来迭代所有内容。

void student_list::deleter()
{
int x;
cout<<"test"<<endl;
while(head!=NULL)
    {
    student *next = head->next; // Store the next item now.
    cout<<head->id<<endl;
    head->next=NULL;
    delete head;
    head=next;
    }
}

答案 1 :(得分:0)

为了删除或插入单链表中的项,常见的建议是维护两个指针,一个指针用于当前节点,另一个用于前一个节点。

在删除的情况下,操作将是:

// Make the previous node point the the node that
// the next node points to.
p_node->next = p_present->next; 

// Null out the link field of the present node,
// for safety purposes.
p_present->next = NULL;

// Delete the present node.
delete p_present;

我故意在这里遗漏了一些重要的错误。

答案 2 :(得分:0)

删除功能有错误

void student_list::deleter()
{
......
while(walk!=NULL)
    {
    ......
    delete head;
    head->next=NULL;
    ......
    }
 }

您必须重新订购删除/分配

void student_list::deleter()
{
int x;
student *walk;
walk=head;
cout<<"test"<<endl;
while(walk!=NULL)
    {
    cout<<walk->id<<endl;
    walk = walk->next;
    delete head;
    head = walk;
    }
}