【发布时间】:2016-12-21 03:38:52
【问题描述】:
#include<iostream>#include<string>#include<algorithm>using namespace std;class sequence{
struct node{
string name;
string data;
struct node * next;};
sequence();
~sequence();
void print(struct node *);
struct node *sortlist(struct node *);
struct node *deletenode(struct node *, string);
struct node *searchnode(struct node *, string);
struct node *insertnode(struct node *, string);};
void print(struct node *st){ //打印链表的方法
while(st!=0){
cout<<st->data<<endl;
st=st->next;}}
struct node *deletenode(struct node *st, string x){//删除包含元素x的节点
struct node *s1=st, *t,*ptr;
string m=x;
ptr=st;
if (s1==0)// if linked list is empty {
cout<<"linkedlist empty"<<endl;}
else if(s1->next==0)//if linked list contains only one element
{
if(s1->data==m)
{
free(s1);
s1=0;}
else
cout<<m<<"is not in the list."<<endl;
}
else if(s1->next!=0&&s1->data==m)
{
t=s1->next;
free(s1);
s1=t;
}
else
{
while(s1->data!=m&&s1->next!=0)
{
t=s1;
s1=s1->next;
}
if(s1->data==m)
{
t->next=s1->next;
free(s1);
s1=t;
}
else
cout<<m<<"is not in the list."<<endl;
}
return(ptr);
}
int main(){
sequence obj=new sequence();
struct node *root1, *root2, *root3, *s, *p,*t;
string v;
root1= new node;
root2= new node;
root3= new node;
s=root1;
root1->next=root2;
root2->next=root3;
root3->next=0;
root1->data="man";//data in the nodes of linked list
root2->data="aan";
root3->data="van";
root1->name="1";
root2->name="2";
root3->name="3";
cout<<"enter the string :";
cin>>v;
cout<<endl;
p=obj.deletenode(s, v);// delete node function call
obj.print(p);
return(0);}
问题 1:当我运行此代码时,它在 deletenode 方法中执行错误,它不是删除链表的第一个元素,而是删除所有其他元素。请告诉我我在代码中哪里出错了。
问题 2:我试图用上面提到的所有方法、构造函数和析构函数创建一个类,但是当我运行此代码时,我收到诸如 “不完整类型'结构节点'的无效使用”之类的错误。我是类概念的新手,请指导我在这段代码中哪里出错了。
抱歉没有正确的格式。 期待一个肯定的答复。
【问题讨论】:
-
很抱歉,但似乎没有人想了解您的 1000 行代码。请为问题(和答案)制作一个对所有人有用的更简单示例。
-
^换句话说:请发布一个minimal reproducible example 来重现您的问题。
-
Maks,阅读How to Ask。您需要提供minimal reproducible example 供人们使用。在这种情况下,我会强调“最小”。当您需要帮助调试时,您还应该将实际的错误输出放入您的问题中。
-
当您制作较小版本的问题时,请修复您的代码格式。
-
"如果整个代码不存在,那么你怎么会明白我遇到了什么错误。我提供整个代码只是为了更容易测试和评论。"您没有阅读给您的链接。一个 MCVE 是“完整的代码”,它可以完全重现问题并包含所有必要的信息……但它不是您的原始真实代码,它包含 990 行完全不相关的行。再次阅读有关构建minimal reproducible examples 的信息。我们需要它的另一个原因是,如果您没有 MCVE,那么您还无法自己正确调试问题,只能让我们为您解决问题。
标签: c++