题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include<stdio.h> #include<string.h> #include <stdlib.h> struct ListNode { int m_nKey; struct ListNode* m_pNext; }; int main(){ int count = 0; //循环读入 while(scanf("%d\n",&count)!=EOF){ //构建链表 struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->m_pNext = NULL; struct ListNode* q = head; for(int i =0; i<count; i++){ struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode)); int n = 0; scanf("%d ",&n); temp->m_nKey = n; q->m_pNext = temp; q = q->m_pNext; } q = head; int k = 0; scanf("%d\n",&k); //快指针,先走k步 for(int i = 0; i < k;i++){ q = q->m_pNext; //printf("%d\n",q->m_nKey); } //同时前进,一直到最后 while(q!=NULL){ head = head->m_pNext; q = q->m_pNext; } //此时,头指向倒数第k个 printf("%d\n",head->m_nKey); } return 0; }