题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <stdio.h> #include <string.h> #include <stdlib.h> struct list { int val; struct list* next; }; int del_list(struct list *head) { struct list *tmp,*tmp_next; if (head->next == NULL) { /* 只有头结点 */ return 0; } tmp = head->next; while (tmp->next != NULL) { tmp_next = tmp->next; free(tmp); tmp = tmp_next; } free(tmp); return 0; } int inset_node(struct list *head, struct list *new) { struct list *tmp; tmp = head; while (tmp->next != NULL) { tmp = tmp->next; } tmp->next = new; return 0; } int find_node(struct list *head, int pos) { int i; struct list *tmp; tmp = head->next; for (i = 0; i < pos; i++) { tmp = tmp->next; } printf("%d \n", tmp->val); return 0; } int main() { int i, k,tmp_val = 0; int cnt = 0; struct list head, *new; memset(&head, 0, sizeof(struct list)); /* 每个用例 分三次读取,第一次读取总数,第二循环读取节点,第三次读取k值 */ while (scanf("%d", &cnt) != EOF) { for (i = 0; i < cnt; i++) { scanf("%d", &tmp_val); /* */ new = (struct list *) malloc(sizeof(struct list)); if (new == NULL) { del_list(&head); return -4; } /* 构造新的节点,作为最后一个节点 */ new->val = tmp_val; new->next = NULL; inset_node(&head, new); } /* 输入k值 */ scanf("%d", &k); if (k > cnt) { continue; } /* 计算出节点位置,直接正向查找 */ find_node(&head, cnt - k ); /* 别内存泄漏 */ del_list(&head); head.next = NULL; } return 0; }