查找元素(线性表)
时间: 1ms 内存:128M
描述:
(线性表)试编写一个算法,在带表头结点的单链表中寻找第i个结点。若找到,则函数返回第i个结点的地址;若找不到,则函数返回0。
输入:
2 3 4 5 6 7 8 9
1
输出:
0
示例输入:
2 3 4 5 6 7 8 9
10
示例输出:
0
提示:
参考答案(内存最优[752]):
#include <stdio.h>
#include <stdlib.h>
typedef struct shu
{
int date;
struct shu *link;
}SHU;
SHU *creat()
{
SHU *head,*p,*q;
head=p=q=malloc(sizeof(SHU));
scanf("%d",&p->date);
while(getchar()!='\n')
{
p=malloc(sizeof(SHU));
scanf("%d",&p->date);
q->link=p;
q=p;
}
q->link=NULL;
return head;
}
int play(SHU *head,int n)
{
SHU *p=head;
int i=1;
while(p!=NULL)
{
if(i++==n)
break;
p=p->link;
}
if(p==NULL)
return 0;
else
return n-1;
}
int main()
{
int n;
SHU *head;
head=creat();
scanf("%d",&n);
printf("%d",play(head,n));
return 0;
}
参考答案(时间最优[0]):
#include <stdio.h>
#include <stdlib.h>
typedef struct shu
{
int date;
struct shu *link;
}SHU;
SHU *creat()
{
SHU *head,*p,*q;
head=p=q=malloc(sizeof(SHU));
scanf("%d",&p->date);
while(getchar()!='\n')
{
p=malloc(sizeof(SHU));
scanf("%d",&p->date);
q->link=p;
q=p;
}
q->link=NULL;
return head;
}
int play(SHU *head,int n)
{
SHU *p=head;
int i=1;
while(p!=NULL)
{
if(i++==n)
break;
p=p->link;
}
if(p==NULL)
return 0;
else
return n-1;
}
int main()
{
int n;
SHU *head;
head=creat();
scanf("%d",&n);
printf("%d",play(head,n));
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。