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;
}