3-05. 寻求倒数第二链线性表K项目(15)(STL list应用 ZJU_PAT)
主题链接:http://pat.zju.edu.cn/contests/ds/3-05
给定一系列正整数,请设计一个尽可能高效的算法。查找倒数第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 |
PS:
不是太了解list运用的童鞋请猛戳:http://blog.csdn.net/u012860063/article/details/39784005
代码例如以下:
#include <cstdio> #include <cstring> #include <algorithm> #include <list> using namespace std; int main() { list<int> LIST; int k, tt; int cont = 0; int ans = -1; scanf("%d",&k); while(1) { scanf("%d",&tt); if( tt < 0) break; LIST.push_back(tt); cont++; if(cont >= k) { ans = LIST.front(); LIST.pop_front(); } } if(ans == -1) printf("NULL\n"); else printf("%d\n",ans); return 0; }
版权声明:本文博客原创文章,博客,未经同意,不得转载。