HBU DS 1-6 求链式线性表的倒数第K项 (20分)
给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式:
输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL
。
输入样例:
4 1 2 3 4 5 6 7 8 9 0 -1
输出样例:
7
这道题刚开始准备先正序生成链表,然后再将链表逆置,后来一想,其实构建链表的时候就可以倒着插入。后来过了两天上数据结构课的时候,发现这就是头插法,原来插入数据有两种方式,一种头插,一种尾插。
还有就是,这个题卡住我了,后俩测试点一直超时,然后我突然想到了暑假培训里学长说过,cin,cout比scanf,printf要费时很多。或者加上那个 **std::ios::sync_with_stdio(false);**时间就会变短,然后我加上之后,突然就都过了。呼~
代码
#include <iostream>
using namespace std;
typedef struct Node *List;
struct Node
{
int data;
List next;
};
void FindKth(List l, int k)
{
List temp = l;
for (int i = 1; i <= k && temp; i++)
{
if (i == k)
{
cout << temp->data;
return;
}
temp = temp->next;
}
cout << "NULL";
}
int main()
{
std::ios::sync_with_stdio(false);
int X;
cin >> X;
int currNum;
List temp = nullptr;
List pre = nullptr;
while (cin >> currNum)
{
if (currNum < 0)
break;
List currNode = (List)malloc(sizeof(Node));
currNode->next = nullptr;
currNode->data = currNum;
currNode->next = pre;
pre = currNode;
}
FindKth(pre, X);
}