问题及代码:
知识点总结:
判断链表中是否有值为x的结点。
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:words.cpp
*作 者:单昕昕
*完成日期:2015年1月17日
*版 本 号:v1.0
*
*问题描述:编写函数,输出链表中是否有值为x的结点。
*程序输入:若干正数(以0或一个负数结束)建立链表。
*程序输出:所输入的数和判断结果。
*/
#include <iostream>
using namespace std;
struct Node
{
int data; //结点的数据
struct Node *next; //指向下一结点
};
Node *head=NULL; //将链表头定义为全局变量,以便于后面操作
void make_list(); //建立链表
void out_list(); //输出链表
int main( )
{
make_list();
out_list();
return 0;
}
void make_list()
{
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=p;
cin>>n;
}
return;
}
void out_list()
{
Node *p=head;
int flag=0;
cout<<"请输入要查找的值:";
int x;
cin>>x;
cout<<"链表中的数据为:"<<endl;
while(p!=NULL)
{
if(p->data==x) //查找是否有值为x的结点
flag=1;
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
if(flag==1)
cout<<"在链表中有值为"<<x<<"的结点"<<endl;
else
cout<<"在链表中没有值为"<<x<<"的结点"<<endl;
return;
}
运行结果:
知识点总结:
判断链表中是否有值为x的结点。
学习心得:
感觉用户体验应该不是很好,能再改进改进。