问题及代码:
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:test.cpp
*作者:陈文青
*完成日期:2015年1月19日
*版 本 号:v1.0
*
*问题描述:编写函数void search(int x),输出链表中是否有值为x的结点。
*程序输入:
*程序输出:
*/
#include <iostream>
using namespace std;
struct Node
{
int data; //结点的数据
struct Node *next; //指向下一结点
};
Node *head=NULL; //将链表头定义为全局变量,以便于后面操作
void out_list(); //输出链表
void make_list2();
void search(int x); //查找链表值
int main( )
{
make_list2();
out_list();
int n;
cout<<"该链表是否含有节点,其节点值为:";
cin>>n;
search(n);
return 0;
}
void out_list()
{
Node *p=head;
cout<<"链表中的数据为:"<<endl;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return;
}
void make_list2()
{
int n;
Node *p,*q;
cout<<"输入若干正数(以0或一个负数结束)建立链表:";
cin>>n;
while(n>0) //输入若干正数建立链表,输入非正数时,建立过程结束
{
p=new Node; //新建结点
p->data=n;
p->next=NULL; //新建的结点指向原先的链表头
if(head==NULL)
head=p; //链表头赋值为新建的结点
else
q->next=p; //q记住上一个开辟的结点<span style="font-family: Arial, Helvetica, sans-serif;">,p用来建立下一个结点 </span>
q=p;
cin>>n;
}
return;
}
void search(int x)
{
Node *p=head;
bool a=false; //当超找到所查值时,a=true
while(p!=NULL)
{
if(x==p->data)
a=true;
p=p->next;
}
if(a)
cout<<"是";
else
cout<<"否";
return;
}
运行结果:
知识点总结:
输出链表中是否有值为x的结点。