题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
#include <stdio.h>
#include <malloc.h>
//链表定义
struct ListNode
{
int m_nKey;
struct ListNode* m_pNext;
};
struct ListNode * creatList(struct ListNode* head,int count){
int val=0;
if(count==0){
return NULL;
}
//构建链表头
head=(struct ListNode*)malloc(sizeof(struct ListNode)*1);
head->m_pNext=NULL;
//保存头结点
struct ListNode* p=head;
scanf("%d",&val);p->m_nKey=val;
struct ListNode* new=NULL;
struct ListNode* pre=head;
//循环建立链表
while(count-1){
scanf("%d",&val);
new=(struct ListNode*)malloc(sizeof(struct ListNode)*1);
new->m_pNext=NULL;
new->m_nKey=val;
p->m_pNext=new;
p=p->m_pNext;
count--;
}
return head;
}
struct ListNode * searchK(struct ListNode* head,int k){
struct ListNode * p=head;
struct ListNode * pre=head;
//从头开始遍历,先遍历k个节点
p=head;//回复起点位置
while(k&&p){
p=p->m_pNext;
k--;
}
//如果k不等于0,直接返回
if(k!=0){
return NULL;
}else{
//定义一个指针变量开始从头走
while(p){
p=p->m_pNext;
pre=pre->m_pNext;
}
}
//最后pre的值就是倒数第k个的值
return pre;
}
int main() {
int count=0,val=0,k=0;
//输入count的值
while(scanf("%d",&count)!=EOF){
struct ListNode* head=creatList(head,count);
//建立链表完成以后输入k
scanf("%d",&k);
//找到k
struct ListNode* s=searchK(head,k);
if(s!=NULL){
printf("%d\n",s->m_nKey);
}
}
return 0;
}
#华为笔试#

