#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<windows.h>
#define N 10
#define Null 0
typedef struct node{
char name[20];
struct node *Previous,*Next;
}student;//用typedef语句后,用student表示struct node
student *create(int n){
student *p,*h,*s;//h是head的缩写是链表头元素,s是用来存新建元素的变量,p是用来不断移动配合链接的临时变量
int i;
if((h=(student *)malloc(sizeof(student)))==Null){
printf("不能分配内存空间!\n");
}
h->name[0]='\0';
h->Previous=Null;
h->Next=Null;
p=h;
for(i=0;i<n;i++){
if((s=(student *)malloc(sizeof(student)))==Null){
printf("不能分配内存空间!\n");
exit(0);
}//如果内存空间不能分配就退出程序
p->Next=s;
printf("请输入第%d个人的姓名\t",i+1);
scanf("%s",&s->name);
s->Previous=p;
s->Next=Null;
p=s;
}
h->Previous=p;
p->Next=h;
return (h);
}
int search(student *h,char *x){//*x是要搜索的人的姓名字符串的地址,代表这条字符串
int n=0;
student *p;//不断移动的临时指针
char *y;//临时用来比较判断的字符串指针
p=h->Next;//链表头元素name是"\0",所以从第二个结点开始
while(p!=h){
n++;
y=p->name;
if(strcmp(y,x)==0)return(n);
else p=p->Next;
}
printf("没有查找到该数据!\n");//当在整条链表中没找到对应结点时才会执行到这一条语句
}
void print(student *h){
student *p;//临时指针
p=h->Next;//从第二个结点开始
printf("数据信息为:\n");
while(p!=h){//输出到头节点之前也就是尾结点
printf("%s\n",p->name);
p=p->Next;
}
printf("\n");
}
int main(){
int number,searchpoint;//存长度值和搜索值
char studname[20];//搜索依据的字符串
student *head;
number=N;//链表长度为10
system("cls");//清屏
system("time/t");//显示系统时间
head=create(number);
print(head);
printf("输入你要寻找的人的名字\n");
scanf("%s",&studname);
//system("cls");
searchpoint=search(head,studname);//获取到字符串对应序号
printf("%d\n",searchpoint);//输出序号
return 0;
}
双向链表-查找
最新推荐文章于 2022-10-27 10:54:22 发布