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

求链式线性表的倒数第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的情况

猜你喜欢

转载自blog.csdn.net/ljhsq/article/details/115446091