p指针指向首元结点(p=L->next),循环结束条件为p是空。
#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>
using namespace std;
#define ERROR 0
typedef struct LNode {
int data; //结点的数据域
struct LNode *next; //结点的指针域
} LNode, *List; //List为指向结构体LNode的指针类型
void InitList(List &L); //创建链表(带头结点)
void ListInput(List &L, int n); //链表数据的输入
void ListOutput(List L); //输出List
bool LocateElem(List L, int e); //判断List里有没有e这个元素
int main()
{
int n;//定义链表中输入元素的个数
int e;
List LA;
InitList(LA);
cin>>n;
ListInput(LA, n);
cin>>e;
if(LocateElem(LA, e))
cout<<"include";
else cout<<"none";
return 0;
}
void ListInput(List &L, int n) //链表数据的输入
{
int i=1;
List p, r;
r = L;
while (i<=n) {
p = new LNode;
cin >> p->data;
p->next = NULL;
r->next = p;
r = p;
i++;
}
}
void ListOutput(List L) //输出List
{
List p;
p = L->next;
cout << "The List is:"<<endl;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void InitList(List &L) //创建链表
{
L = new LNode;
L->next = NULL;
}
//查找线性表中是否包含元素e
bool LocateElem(List L, int e)
{
List p;
InitList(p);
p=L->next;
while(p!=NULL)
{
if(p->data==e)
{
return true;
}
p=p->next;
}
return false;
}