题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
/*
*注意题目中提到构建单向链表后需要忘记长度
*/
struct ListNode
{
int m_nKey;
struct ListNode* m_pNext;
};
int main() {
int num=0,i=0,output=0;
struct ListNode *tmp=NULL,*head=NULL,*rear=NULL;
while (scanf("%d", &num) != EOF) {
head=(struct ListNode *)malloc(sizeof(struct ListNode));
head->m_nKey=0;head->m_pNext=NULL;
rear=head;
for(i=0;i<num;++i)
{
rear->m_pNext=(struct ListNode*)malloc(sizeof(struct ListNode));
rear=rear->m_pNext;rear->m_pNext=NULL;
scanf("%d", &rear->m_nKey);
}
scanf("%d",&output);
tmp=head->m_pNext;num=0;
while(tmp)
{
num++;tmp=tmp->m_pNext;
}
if(output>num)
{
printf("");
}
else {
tmp=head->m_pNext;
for(i=0;i<num-output;++i)
{
tmp=tmp->m_pNext;
}
printf("%d\n",tmp->m_nKey);
}
}
return 0;
}
查看7道真题和解析
