双向链表-查找

#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;
}

这里写图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值