题目:
输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第1个结点为链表的尾指针。
代码:
#include <cstdio> #include <cstdlib> /* 收藏原因:主要可以熟悉用C语言建立链表的过程 */ struct Node{ int val; struct Node *next; }; int main(){ int i, n, t; Node *head, *p, *q; while(scanf("%d", &n) != EOF){ head = (struct Node*)malloc(sizeof(Node)); head->next = NULL; p = head; for(i=0; i<n; i++){ q = (struct Node*)malloc(sizeof(Node)); scanf("%d", &t); q->val = t; p->next = q; p = q; } scanf("%d", &t); if(t>n){ printf("NULL "); continue; }else if(t < 1){ printf("%d ", t); continue; } p = head->next; q = p; while(t--) p = p->next; while(p != NULL){ p = p->next; q = q->next; } printf("%d ", q->val); } return 0; }