题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Link { int elem; struct Link* next; }link; link* initlink(int n) { link* pnew, * head, * ptail; pnew = (link*)malloc(sizeof(link)); scanf("%d", &pnew->elem); head = pnew; ptail = pnew; for (int i = 1; i < n; i++) { pnew = (link*)malloc(sizeof(link)); scanf("%d", &pnew->elem); ptail->next = pnew; ptail = pnew; } ptail->next = NULL; return head; } int main(void) { int n; int k; while (scanf("%d", &n) != EOF) { link* p; link* p1; p = initlink(n); p1 = p; scanf("%d", &k); //计算链表长度 int cnt = 1; while (p->next != NULL) { cnt++; p = p->next; } int j; j = cnt - k; while (j != 0) { p1 = p1->next; j--; } /*for (int j = 0; j < cnt; j++) { printf("%d", p1->elem); p1 = p1->next; }*/ printf("%d\n", p1->elem); } return 0; }