給定一系列正整數,請設計一個盡可能高效的算法,查找倒數第K個位置上的數字。
輸入格式:
輸入首先給出一個正整數K,隨后是若干正整數,最后以一個負整數表示結尾(該負數不算在序列內,不要處理)。
輸出格式:
輸出倒數第K個位置上的數據。如果這個位置不存在,輸出錯誤信息NULL
。
輸入樣例:
4 1 2 3 4 5 6 7 8 9 0 -1
輸出樣例:
7
代碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node *Node; struct Node { int data; Node Next; }; int main() { int n,d,c = 0; scanf("%d",&n); Node temp = (Node)malloc(sizeof(struct Node)),q; temp -> Next = NULL; q = temp; while(scanf("%d",&d)!=EOF&&d >= 0) { Node p = (Node)malloc(sizeof(struct Node)); p -> data = d; p -> Next = NULL; q -> Next = p; q = p; c ++; if(c >= n) { Node t = temp; temp = temp -> Next; free(t); } } if(c >= n)printf("%d",temp -> data); else printf("NULL"); }