题目名称:单链表倒数第K个结点

我修改了转载代码的中间的那个找倒数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);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值