我修改了转载代码的中间的那个找倒数k个的函数;
题目描述:请填写缺失代码完成程序,实现如下功能:首先根据键盘随机输入,以0结束的若干非零整数建立单链表;然后根据输入的整数K,输出链表倒数第K个结点
输入:1 2 3 4 5 6 7 8 0 3
输出:6
输入:0 2 3 4 5 6 7 8 0 3
输出:NULL
#include <stdio.h>
#include <malloc.h>
struct cell {//单链表结点结构体定义
int x;
struct cell* next;
};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
struct cell* head, * tmp, * p;
head = tmp = p = NULL;
int n;
head=(struct cell*)malloc(sizeof(struct cell));
scanf("%d",&head->x);
tmp=head;
tmp->next=NULL;
if(head->x==0)head=NULL;
else{
do{
p=(struct cell*)malloc(sizeof(struct cell));
scanf("%d",&p->x);
if(p->x==0)break;
tmp->next=p;
tmp=p;
tmp->next=NULL;
}while(p->x!=0);
}
return head;//返回单链表头
}
struct cell * back(struct cell* head, int k) {//求链表倒数第k个结点,head是单链表首结点指针
struct cell *p,*q;
int n=1,i;
if(head==NULL) p=head;
else {
q=head;
while(q->next !=NULL)
{
n++;
q=q->next ;
}
for(i=1;i<=n-k+1;i++)
{
p=head;
head=head->next ;
}
}
return p;
}
void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
struct cell *p;
while(head!=NULL){
p=head;
head=p->next;//必须留一个指向下一个的head和不断变化不断释放改变的另一个指针p;
free(p);
}
}
int main(void) {
struct cell* head,*result;
int k;
head = build();
scanf("%d", &k);
result = back(head,k);
if (result != NULL)
printf("%d",result->x);
else
printf("NULL");
release(head);
}