1-6 求链式线性表的倒数第K项 (20分)

1-6 求链式线性表的倒数第K项 (20分)

给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。

输入格式:

输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。

输出格式:

输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL。

输入样例:

4 1 2 3 4 5 6 7 8 9 0 -1

输出样例:

7

代码如下:
数组大法好,数组随机访问效率更高

#include<bits/stdc++.h>
using namespace std;
int num[10000005];
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int K,n,i=0;
	cin >> K;
	cin >> n;
	while(n>=0){
		num[i++] = n;
		cin >> n;
	}
	if(K>i) cout << "NULL" << endl;
	else cout << num[i-K] << endl;
	return 0;
}

双指针法(快慢指针法):
不管正数n个还是倒数n个,其实都是距离-标尺问题。如果我们用两个指针,并保持他们的距离为n,当标尺的右端指向末尾结点时,左端节点就指向倒数第n个结点。
快慢指针是指步长的快慢。
效率果然没数组高

#include<bits/stdc++.h>
using namespace std;
typedef struct Node *LinkList;
typedef struct Node{
	int data;
	struct Node *next;
}Node;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	LinkList L = new Node();L->next=NULL;
	LinkList r = L;
	int K,n,i=0;
	cin >> K;
	cin >> n;
	while(n>=0){
		struct Node *P=(struct Node *)malloc(sizeof(struct Node));
		P->data = n;P->next=NULL;
		r->next = P;r = P;
		cin >> n;
	}
	LinkList first = L;
	while(i<K&&first->next){
		i++;
		first = first->next;
	}
	if(first->next==NULL&&i<K){
		cout << "NULL" << endl;
	}else {
        LinkList second  = L;
        while(first){
            second = second->next;
            first = first->next;
        }
        cout << second->data << endl;
    }
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值