给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字
//有部分测试未通过
#include <iostream>
using namespace std;
long int a[1000005];
typedef struct Node
{
int data = 0;
struct Node* next = NULL;
}Mylist;
void search(Mylist* node, int k)
{
int i=0,j=1;
Mylist* list1 = node; //为临时节点赋值
Mylist* list2 = node;
list1 = list1->next;
while (0 <= (list1->data)) //判断
{
list1 = list1->next;
j = j + 1;
}
if (j < k)
{
cout << NULL;
}
else
{
list2 = list2->next;
for (i = 0; i <= (j-k-2);i++)
{
list2 = list2->next;
}
cout << list2->data;
}
}
int main()
{
int k = 0, i = 0, j = 0;
cin >> k;
Mylist* head,*p;
head = new Mylist;
p = head;
for(i=0;i<1000005;i++)
{
cin >> a[i];
if (a[i] < 0)
break;
}
for (j = 0; j <= i; j++)
{
Mylist* newlist = new Mylist; //创建新节点
newlist->data = a[j]; //为新节点赋值
head->next = newlist; //老节点接新节点
head = newlist; //更新节点以便下次遍历
}
search(p,k);
return 0;
}
网友评论