好的,这是我在单链表上的训练,作为一个新手......但是,我必须在某个地方搞砸了。我的代码非常简单,包含您期望的所有典型过程。
问题:
即使我输入不在列表中的数字,我的布尔函数也始终为真
这是我的代码,同时查看 main 函数以了解事情发生的顺序。哦,谢谢你的帮助!!:)
#include <string>
#include <iostream>
using namespace std;
class Node
{
public:
int n;
Node* link;
};
void display(Node* head)
{
cout<<head->n<<" ";
while(head->link!=NULL)
{
head=head->link;
cout<<head->n<<" ";
}
cout<<endl;
}
void addnode(Node*& head, int x)
{
if(head==NULL)
{
head=new Node;
head->n=x;
head->link=NULL; // Necessary? Why?
}
else
{
Node* p=new Node;
p->n=x;
p->link=head;
head=p;
}
}
bool found(Node* head, int x)
{
if(head->n==x) return true;
while(head->link!=NULL)
{
head=head->link;
if(head->n==x) return true;
}
return false;
}
void addtail(Node*& head, int x)
{
if(head==NULL)
{
head=new Node;
head->n=x;
head->link=NULL;
}
else
{
Node* q=NULL;
q=head;
while(q->link!=NULL) q=q->link;
Node* r=new Node;
r->n=x;
r->link=NULL;
q->link=r;
}
}
int removehead(Node*& head)
{
if(head==NULL)
{
cout<<"The list is empty";
return 0;
}
int x;
if(head->link==NULL)
{
x=head->n;
head=NULL;
return x;%0stackoverflow.com
Node* p=NULL;
p=head;
head=head->link;
x=p->n;
delete p;
return x;
}
int removetail(Node*& head)
{
if(head==NULL)
{
cout<<"The list is empty";
return 0;
}
int x;
if(head->link==NULL)
{
x=head->n;
delete head;
Node* head=NULL;
return x;
}
Node* p=NULL;
p=head;
while(p->link!=NULL) p=p->link;
x=p->n;
delete p;
return x;
}
int main()
{
int y; int z;
Node* p=NULL;
while(cin>>y)
{
addnode(p,y);
}
cin.clear(); cin.ignore();
cout<<endl;
display(p);
cout<<endl;
cout<<removehead(p)<<" ";
cout<<removetail(p)<<endl;
display(p);
cout<<endl<<"give me a number:";
cin>>z;
if(found) cout<<endl<<"found";
else cout<<endl<<"not found";
}