#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方法中的错误,它不会删除链表的第一个元素,而是删除其他所有元素。请告诉我代码中出错的地方。< / p>
问题2:我试图创建一个包含所有上述方法,构造函数和析构函数的类,但是当我运行此代码时,我遇到的错误如&#34;无效使用不完整类型&# 39; struct node&#39;&#34; 。我是班级概念的新手,请指导我在这段代码中出错的地方。
没有正确格式的道歉。 寻找肯定的答复。
答案 0 :(得分:-1)
你不应该在类定义中定义一个完整的结构 而不是这样做公开定义结构并在类中包含它的实例。希望这有助于
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct node{ //structure definition outside the class
string name;
string data;
struct node * next;
};
class sequence{
node node1; //define a node variable
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);};enter code here