Link: http://pat.zju.edu.cn/contests/ds/3-05
For a series of positive integers, design an algorithm that is as efficient as possible to find the number at the last K position.
Input format description:
The input first gives a positive integer k, followed by several positive integers, and finally ends with a negative integer (the negative number is not included in the sequence, do not process ).
Output format description:
Output data at the last K position. If this location does not exist, the output error message is "null ".
Sample input and output:
Serial number |
Input |
Output |
1 |
4 1 2 3 4 5 6 7 8 9 0 -1 |
7 |
2 |
6 3 6 7 8 2 -2 |
NULL
|
PS:
Not too familiar with the use of list shoes please stamp: http://blog.csdn.net/u012860063/article/details/39784005
The Code is as follows:
#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;}
3-05. Calculate the last K of the chained linear table (15) (used by STL List)