一个数据结构 设计题

来源:百度知道 编辑:UC知道 时间:2024/05/28 17:25:56
设计题:

“ 编写一个在已经建立好的单链表(表头指针为head )中查找元素值为 X的算法 。(要求给出结点的结构) ”

#include<iostream>
using namespace std;
struct list
{
int data;
list *next;
};
list *head=NULL;
list *create()//创建链表
{
list *p,*q;

int num;
cout<<"input the data:"<<endl;
cin>>num;

do{
p=new list;
p->data=num;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
cin>>num;
}while(num!=-1);
if(head!=NULL)
q->next=NULL;
return head;
}
void search(list *head)//查找元素
{
int data,location=0;
cout<<"\ninput the data you want to search:"<<endl;
cin>>data;
while(head!=NULL)
{
if(head->data==data)
{
cout<<"its location is:"<<endl;
cout<<location<<endl;
return;
}
else {
location++;
head=head->next;
}<