PTA 单链表元素定位
来源:互联网 发布:增强网络安全意识 编辑:程序博客网 时间:2024/06/07 23:20
//库函数头文件包含#include<stdio.h>#include<malloc.h>#include<stdlib.h>//函数状态码定义#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW -2typedef int Status;typedef int ElemType; //假设线性表中的元素均为整型typedef struct LNode{ ElemType data; struct LNode *next;}LNode,*LinkList;Status ListCreate_L(LinkList &L,int n){ LNode *rearPtr,*curPtr; //一个尾指针,一个指向新节点的指针 L=(LNode*)malloc(sizeof (LNode)); if(!L)exit(OVERFLOW); L->next=NULL; //先建立一个带头结点的单链表 rearPtr=L; //初始时头结点为尾节点,rearPtr指向尾巴节点 for (int i=1;i<=n;i++){ //每次循环都开辟一个新节点,并把新节点拼到尾节点后 curPtr=(LNode*)malloc(sizeof(LNode));//生成新结点 if(!curPtr)exit(OVERFLOW); scanf("%d",&curPtr->data);//输入元素值 curPtr->next=NULL; //最后一个节点的next赋空 rearPtr->next=curPtr; rearPtr=curPtr; } return OK;}//下面是需要实现的函数的声明int ListLocate_L(LinkList L, ElemType x);int main(){ LinkList L; int n; int x,k; scanf("%d",&n); //输入链表中元素个数 if(ListCreate_L(L,n)!= OK) { printf("表创建失败!!!\n"); return -1; } scanf("%d",&x); //输入待查找元素 k=ListLocate_L(L,x); printf("%d\n",k); return 0;}/* 请在这里填写答案 */int ListLocate_L(LinkList L, ElemType x){/*思路:从头结点开始找,若结点数据域的值不等于x则后移,设置计数器记录位序,若相等则返回位序*/ LNode *curPtr = L->next; int i=1; while(curPtr->next != NULL) { if(curPtr->data != x) { curPtr =curPtr->next; i++; } else return i; } return 0;}
测试数据:
input:
4
1 2 3 4
1
output:1
阅读全文
0 0
- PTA 单链表元素定位
- PTA 数据结构 6-2 单链表元素定位
- PTA 6-2 单链表元素定位(12 分)
- 单链表元素定位
- 单链表元素定位
- 6-2 单链表元素定位
- 元素定位
- 元素定位
- 元素定位
- 元素定位
- 定位元素
- 定位元素
- 元素定位
- 元素定位
- 单链表元素定位(输出链表中元素的下标)
- PTA
- PTA
- pta
- Spring Boot 整合 RabbitMQ 之 Direct模式 (一)
- Java连接MySql数据库警告:Establishing SSL connection without server's identity verification is not recommend
- wait()和notify()
- desc 排序避免空值问题
- 单利模式
- PTA 单链表元素定位
- Linux服务器映射到本地磁盘
- PostgreSQL学习手册(客户端命令<一>)
- Ubuntu下搭建ngrok服务器及客户端
- 在公司的学习笔记
- 未来数据分析市场走向预测
- Go语言开发工具
- iOS 11及iPhone X适配
- 3DMAX三维制作地形图教程