求链式线性表的倒数第K项
题目要求:
给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式:
输入首先给出一个正整数K,随后是若干正整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL。
输入样例:
4 1 2 3 4 5 6 7 8 9 0 -1
输出样例:
7
Code:
#include <stdio.h>
#include <stdlib.h>
struct list {
int data;
struct list *next;
};
int randlist(struct list *L);
void getlist(struct list *L, int _num);
int main(void)
{
int num, cnt, _num;
scanf("%d", &num);
struct list *L;
L = (struct list *)malloc(sizeof(struct list));
cnt = randlist(L);
_num = cnt-num+1;
if(_num <= 0) {
printf("NULL");
}
else{
getlist(L, _num);
}
return 0;
}
int randlist(struct list *L)
{
int x, cnt = 0;
struct list *h, *s, *p;
h = (struct list *)malloc(sizeof(struct list));
h = L;
s = h;
scanf("%d", &x);
while(x >= 0) {
cnt ++;
p = s;
s->data = x;
s = (struct list *)malloc(sizeof(struct list));
p->next = s;
scanf("%d", &x);
}
p->next = NULL;
return cnt;
}
void getlist(struct list *L, int _num)
{
struct list *p;
int n = 0;
p = L;
while(p) {
n ++;
if(n == _num) {
printf("%d", p->data);
break;
}
p = p->next;
}
}