题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
不知道为什么会用链表,但是既然要求了,那就这么写
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode{
int m_nKey;
struct ListNode* m_pNext;
} node;
int main(){
int number;
int k;
while(scanf("%d", &number) != EOF){
node* p=(node*)malloc(sizeof(node));
node*last = p;
p->m_nKey = -1;
p->m_pNext = NULL;
for(int i=0; i<number; i++){
node*tmp=(node*)malloc(sizeof(node));
scanf("%d", &tmp->m_nKey);
last->m_pNext = tmp;
last = tmp;
tmp ->m_pNext = NULL;
}
scanf("%d", &k);
if(k==0){
printf("0\n");
}
else{
int loc = number-k+1;
node* loction = p;
for(int i=0; i<loc; i++){
loction = loction->m_pNext;
}
printf("%d\n", loction->m_nKey);
free(p);
}
}
}