【PTA】7-1 求链式线性表的倒数第K项

链式线性表操作:找到倒数第K个元素
该博客探讨了如何在链式线性表中有效地找到倒数第K个元素的问题,适合数据结构学习者。通过实例和算法解析,阐述了解决这一问题的关键步骤和思路。

题样:

 

// import java.util.ArrayList;
// import java.util.Comparator;
// import java.util.Scanner;
// public class Main {
// 	public static void main(String[] args) {
// 		Scanner sc = new Scanner(System.in);
// 	    int[] al = new int[1024];
// 	    int n=sc.nextInt();
// 	    int num=0;
// 	    int a = sc.nextInt();
// 	    for(int i=0;a!=-1;i++) {
// 	    	al[i]=a;
// 	    	a=sc.nextInt();
// 	    	num++;
// 	    }
// 	    if(n>0&&n<=num)System.out.println(al[num-n]);
//         else System.out.println("NULL");
// 	}
// }
#include<stdio.h>
#include<stdlib.h>
struct node{
	int date;
	struct node* next;
};
int main(){
	struct node* list = (struct node*) malloc (sizeof(struct node));
	list->date = 0x7fffffff;
	list->next = NULL;
	long long k;
	scanf("%lld",&k);
	int date;
	while(scanf("%d",&date)!=EOF&&date>=0){
		struct node* newnode = (struct node*) malloc (sizeof(struct node));
		newnode->date=date;
		newnode->next=list->next;
		list->next=newnode;
	}
	long long count = 1;
	struct node* p=list->next;
	while(p!=NULL){
		if(count==k)break;
		else {
			count++;p=p->next;
		}
	}
	if(p!=NULL)printf("%d",p->date);
	else printf("NULL");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值