Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Example Input
10 1 22 33 55 63 70 74 79 80 87 4 55 10 2 87
Example Output
4 No Found! No Found! 10
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define INITLISTSIZE 100000
#define INCREMENT 10
#define OVERFLOW -2
#define ERROR -1
#define OK 1
typedef int Elemtype;
typedef int Statu;
typedef struct node
{
Elemtype *elem;
int length;
int listsize;
} Sqlist;
Statu Initlist(Sqlist &L);
Statu Insertlist(Sqlist &L, int i, int e);
Statu Dellist(Sqlist &L, int i);
int Search(Sqlist L, int g, int l, int r);
Statu Prelist(Sqlist L);
Statu Destroylist(Sqlist &L);
int main()
{
int i, j, m, n;
Sqlist La;
Initlist(La);
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &j);
Insertlist(La, i + 1, j);
}
scanf("%d", &m);
while(m--)
{
scanf("%d", &j);
int k = Search(La, j, 0, n - 1);
if(k >= 0)
printf("%d\n", k + 1);
else
printf("No Found!\n");
}
Destroylist(La);
}
Statu Initlist(Sqlist &L)
{
L.elem = (Elemtype *)malloc(INITLISTSIZE * sizeof(Elemtype));
if(!L.elem)
return OVERFLOW;
L.length = 0;
L.listsize = INITLISTSIZE;
return OK;
}
Statu Insertlist(Sqlist &L, int i, int e)
{
if(i < 1 || i > L.length + 1)
return ERROR;
if(L.length >= L.listsize)
{
L.elem = (Elemtype *)realloc(L.elem, (L.listsize + INCREMENT) * sizeof(Elemtype));
if(!L.elem)
return OVERFLOW;
L.listsize += INCREMENT;
}
for(int j = L.length; j >= i; j--)
L.elem[j] = L.elem[j - 1];
L.elem[i - 1] = e;
++L.length;
return OK;
}
Statu Dellist(Sqlist &L, int i)
{
if(i < 1 || i > L.length)
return OVERFLOW;
for(int j = i - 1; j < L.length; j++)
L.elem[j] = L.elem[j + 1];
--L.length;
return OK;
}
int Search(Sqlist L, int g, int l, int r)
{
int i = l, j = r;
int mid;
if(l <= r)
{
mid = (i + j)/2;
if(g == L.elem[mid])
return mid;
else
{
if(g < L.elem[mid])
return Search(L, g, l, mid - 1);
else
return Search(L, g, mid + 1, r);
}
}
return -1;
}
Statu Prelist(Sqlist L)
{
for(int i = 0; i < L.length; i++)
{
printf("%d%c", L.elem[i], i == L.length - 1 ? '\n' : ' ');
}
return OK;
}
Statu Destroylist(Sqlist &L)
{
if(L.elem)
{
free(L.elem);
L.length = 0;
L.listsize = 0;
}
else
return ERROR;
return OK;
}