给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。
输入格式:
输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内,不要处理)。
输出格式:
输出倒数第K个位置上的数据。如果这个位置不存在,输出错误信息NULL
。
输入样例:
4 1 2 3 4 5 6 7 8 9 0 -1
输出样例:
7
我自己写的一种 超时 然后又参照网上写的两种
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode *List;
typedef int Element;
struct LNode
{
Element Data;
struct LNode *Next;
};
List Insert(List L, Element X, List P)
{
List ptrl, S;
ptrl = L;
if (ptrl == P)
{
S = (List)malloc(sizeof(struct LNode));
S->Data = X;
S->Next = NULL;
return S;
}
while (ptrl->Next != NULL)
{
ptrl = ptrl->Next;
}
S = (List)malloc(sizeof(struct LNode));
S->Data = X;
S->Next = NULL;
ptrl->Next = S;
return L;
}
void print(List L,int i)
{
int k = 1;
while (L&&k<i)
{
k++;
L = L->Next;
}
if (L&&k == i)
printf("%d", L->Data);
else
printf("NULL");
}
int length(List L)
{
List P;
P = L;
int j = 0;
while (P != NULL)
{
P = P->Next;
j++;
}
return j;
}
int main()
{
int n, k;
List L, R;
L = NULL;
scanf("%d", &n);
do
{
scanf("%d", &k);
L = Insert(L, k, NULL);
} while (k>=0);
int k2 = length(L);
int i = k2 - n;
print(L,i);
while (1);
return 0;
}
参照网上写的两种
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode *List;
typedef int Element;
struct LNode
{
Element Data;
struct LNode *Next;
};
List Insert(List L, Element X, List P)
{
List ptrl, S;
ptrl = L;
if (ptrl == P)
{
S = (List)malloc(sizeof(struct LNode));
S->Data = X;
S->Next = ptrl;
return S;
}
while (ptrl->Next != NULL)
{
ptrl = ptrl->Next;
}
S = (List)malloc(sizeof(struct LNode));
S->Data = X;
S->Next = S;
return S;
}
int main()
{
int n, k;
List L, R;
L = NULL;
scanf("%d", &n);
do
{
scanf("%d", &k);
//L = Insert(L, k, L);
List S = (List)malloc(sizeof(struct LNode));
S->Data = k;
S->Next = L;
L = S;
} while (k >= 0);
while (n>0)
{
n--;
L = L->Next;
}
if (L)
printf("%d\n", L->Data);
else
{
printf("NULL\n");
}
while (1);
return 0;
}
感觉使用insrt函数写显得倒麻烦啦