有一个存放整数的长度为m的线性表L,其元素单调递增。从控制台输入一个整数,在线性表中查找这个整数并返回其在表中的位置。如果找不到,返回-1。要求:使用链式存储实现。
2条回答 默认 最新
- CSDN专家-天际的海浪 2022-03-27 23:46关注
用链表存储数据。循环p=p->next在线性表中查找输入的整数即可
你题目的解答代码如下:
#include <stdio.h> #include <stdlib.h> struct Data { int numb; struct Data *next; }; void creat(struct Data *pHead) { int count = 0,n; struct Data *p, *t; pHead->next = NULL; p = pHead; while (count<10) { t = (struct Data *)malloc(sizeof(struct Data)); scanf("%d", &n); t->numb = n; t->next = NULL; p->next = t; p = t; count++; } } int find(struct Data *pHead, int n) { struct Data *p = pHead; int index = 1; //如果第一个元素位置要求是0, 改成 index = 0; while (p->next != NULL) { p = p->next; if (p->numb==n) { return index; } else if (p->numb>n)// 因为是递增数列, 当numb大于n就可以结束循环了 { break; } index++; } return -1; } int main() { struct Data *pHead = (struct Data *)malloc(sizeof(struct Data)); int n; printf("请输入10个递增整数:"); creat(pHead); printf("请输入查找的整数:"); scanf("%d", &n); printf("%d\n", find(pHead,n)); return 0; }
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录