求链式线性表的倒数第K项
给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式:
输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL
。
输入样例:
4 1 2 3 4 5 6 7 8 9 0 -1
输出样例:
7
标程
单链表版
#include<map>
#include<list>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<iomanip>
#include<cstring>
#include<iterator>
#include<iostream>
#include<algorithm>
#define R register
#define LL long long
#define pi 3.141
#define INF 1400000000
using namespace std;
struct Node {
int number;
Node* next;
};
Node* List;
inline int read() {
int number = 0;
int f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') {
f = -1;
}
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
number = number * 10 + ch - '0', ch = getchar();
}
return number * f;
}
int main() {
int k = read();
List = (Node*)malloc(sizeof(Node));
List->next = NULL;
int Data;
Node* point = (Node*)malloc(sizeof(Node));
point = List;
while (scanf("%d", &Data) != EOF) {
if (Data < 0) {
break;
}
Node* temp = (Node*)malloc(sizeof(Node));
temp->number = Data;
temp->next = point->next;
point->next = temp;
}
point = List;
for (R int i = 0; i < k; ++i) {
point = point->next;
}
if (point) {
printf("%d", point->number);
}
else {
printf("NULL");
}
return 0;
}
双向链表版-数据问题
#include<map>
#include<list>
#include<cmath>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<iomanip>
#include<cstring>
#include<iterator>
#include<iostream>
#include<algorithm>
#define R register
#define LL long long
#define pi 3.141
#define INF 1400000000
using namespace std;
#pragma GCC optimize(2)
struct Node {
int number;
Node* next;
Node* front;
};
Node* List;
int main() {
int List_Length = 0;
int k;
scanf("%d", &k);
List = (Node*)malloc(sizeof(Node));
List->next = NULL, List->front = NULL;
int Data;
Node* point = (Node*)malloc(sizeof(Node));
point = List;
Node* temp;
if (k < 1) {
cout << "NULL";
return 0;
}
while (scanf("%d", &Data) != EOF) {
if (Data == -1) {
break;
}
++List_Length;
temp = (Node*)malloc(sizeof(Node));
temp->number = Data;
temp->next = NULL;
temp->front = point;
point->next = temp;
point = temp;
}
if (k < 1 || k > List_Length) {
cout << "NULL";
return 0;
}
if (List_Length - k < k) {
point = List->next;
for (int i = 0; i < List_Length - k; ++i) {
point = point->next;
}
if (point) {
printf("%d", point->number);
}
else {
printf("NULL");
}
}
else {
for (int i = 0; i < k - 1; ++i) {
point = point->front;
}
if (point) {
printf("%d", point->number);
}
else {
printf("NULL");
}
}
return 0;
}