7-19 求链式线性表的倒数第K项
分数 20
全屏浏览题目
切换布局
作者 DS课程组
单位 浙江大学
给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式:
输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL
。
输入样例:
4 1 2 3 4 5 6 7 8 9 0 -1
输出样例:
7
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<bits/stdc++.h>
using namespace std;
typedef struct node{
int data;
int count;
struct node* next;
}node,*List;
void create(List &l){
List p;
l=(node*)malloc(sizeof(node));
l->count=0;
l->next=NULL;
int d;
while(scanf("%d",&d)&&d>=0){
p=(node*)malloc(sizeof(node));
p->data=d;
l->count++;
p->next=l->next;
l->next=p;
}
}
void find(List l,int n){
if(n<1||n>l->count||l->next==NULL){
printf("NULL");
}else{
for(int i=0;i<n;i++){
l=l->next;
}
printf("%d",l->data);
}
}
int main(){
int n;
scanf("%d",&n);
List l;
create(l);
find(l,n);
return 0;
}
若代码有误还请指正!