题解 | #HJ51 输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//注意链表的定义语句
//next处要用struct ListNode*因为ListNode方法还没有定义
//链表的写入 head tail used三个指针;
typedef struct ListNode
{
int m_nKey;
struct ListNode* m_pNext;
}ListNode;
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
ListNode *num, *head,*tail;
head = (ListNode *)malloc(sizeof(ListNode));
head->m_pNext =NULL;
tail = head;
for (int i = 0; i < n; i++)
{
num = (ListNode *)malloc(sizeof(ListNode));
scanf("%d", &num->m_nKey);
num->m_pNext = NULL;
tail->m_pNext = num;
tail = num;
}
head = head->m_pNext;
int search;
scanf("%d", &search);
if (search <= 0 || search > n)
{
printf("0\n");
}
else
{
ListNode *find;
find = head;
for (int i = 0; i < n - search; i++)
{
find = find->m_pNext;
}
printf("%d\n",find->m_nKey);
}
}
return 0;
}