当前位置:主页 > 查看内容

求链式线性表的倒数第K项(两种方法,第二种较好)

发布时间:2021-04-30 00:00| 位朋友查看

简介:求链式线性表的倒数第K项 题目 答案 第一种解法 第二种解法(较好) 注意 题目 答案 第一种解法 这种方法是正常输入然后将链表逆置虽然pta是可以通过的(写数组应该都能通过)但明显没有下一种好 # include stdio.h # include malloc.h struct Node { int data ;……

求链式线性表的倒数第K项

题目

在这里插入图片描述

答案

第一种解法

这种方法是正常输入,然后将链表逆置,虽然pta是可以通过的(写数组应该都能通过),但明显没有下一种好

#include<stdio.h>
#include<malloc.h>
struct Node{
	int data;
	struct Node *next;
}; 
int main()
{
	struct Node *node,*temp,*p,*head,*older,*news;
	int count;
	node=(struct Node *) malloc(sizeof(struct Node));
	head=node;
	int n,t;
	scanf("%d",&n);
	while(1)
	{
		scanf("%d",&t);
		if(t<0) break;
		count++;
		temp=(struct Node *) malloc(sizeof(struct Node));
		temp->data=t;
		temp->next=NULL;
		node->next=temp;
		node=node->next;
	}
	if(count<n) 
	{
		printf("NULL");return 0;
	}
	head=head->next;
	news=NULL;
	older=head;
	while(older)
	{
		temp=older->next;
		older->next=news;
		news=older;
		older=temp;
	}
	count=0;
	while(1)
	{
		count++;
		if(count==n) 
		{
			printf("%d",news->data);return 0;
		}
		news=news->next;
	}
}

第二种解法(较好)

这种解法就是头插法,很简单,我参考了下面这篇文章
https://blog.csdn.net/lovecyr/article/details/90645982

#include<stdio.h>
#include<malloc.h>
struct Node{
	int data;
	struct Node *next;
};
int main()
{
	int k,t,i;
	scanf("%d",&k);
	struct Node *head,*p;
	head=(struct Node *)malloc(sizeof(struct Node));
	head->next=NULL;
	while(scanf("%d",&t)&&t>=0)
	{
		p=(struct Node *)malloc(sizeof(struct Node));
		p->data=t;
		p->next=head->next;
		head->next=p; 
	}
	for(i=0;i<k;i++)
	head=head->next;
	if(head) printf("%d",head->data);
	else printf("NULL");
}

注意

记得NULL的情况

;原文链接:https://blog.csdn.net/ljhsq/article/details/115446091
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐