1021. 求链式线性表的倒数第K项(15)
给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式说明:
输入首先给出一个正整数K,随后是若干正整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式说明:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息“NULL”。
样例输入与输出:
序号 | 输入 | 输出 |
1 | 4 1 2 3 4 5 6 7 8 9 0 -1 | 7 |
2 | 6 3 6 7 8 2 -2 | NULL |
#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node *next;
};
int n,m;
struct node *creat(void)
{
struct node *head,*p1,*p2;
head=NULL;
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->num);
m=0;
while(p1->num>=0)
{
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->num);
++m;
}
p2->next=NULL;
return head;
}
void print(struct node *head,int f)
{
if(f>m)
{
printf("NULL\n");
return;
}
else
{
int f1=0,m1;
f1=m-f;
m1=0;
while(head!=NULL)
{
if(m1==f1)
{
printf("%d",head->num);
break;
}
else
{
m1++;
head=head->next;
}
}
printf("\n");
}
}
int main()
{
struct node *p;
scanf("%d",&n);
p=creat();
print(p,n);
return 0;
}