顺序表查找

#include<stdio.h>
#include<stdlib.h>

#define EQ(a,b) ((a) == (b))
#define LT(a,b) ((a) < (b))
#define LE(a,b) ((a) <= (b))
typedef struct{
	int key;
	int data;
}SElemType;

typedef struct{
	SElemType *elem;
	int length;
}SSTable;

SSTable * create(int n)
{
	SSTable *sst = (SSTable *)malloc(sizeof(SSTable));
	int x;
	sst->elem = (SElemType*)malloc(sizeof(SElemType) * n);
	sst->length = n;
	for(int i = 1; i <= n ; i++)
	{
		scanf("%d",&x);
		sst->elem[i].data = x;
		sst->elem[i].key = i;
	}
	sst->elem[0].key = 0;
	sst->elem[0].key = 0;
	return sst;
}

int search(SSTable * st,int key)
{
	int i;
	st->elem[0].key = key;
	for( i = st->length ;!EQ(st->elem[i].key,key);--i);
	return i;
}

void main()
{
	printf("Input number of element:\n");
	int n;
	scanf("%d",&n);
	SSTable * sst = create(n);
	printf("the search table element are:\n");
	for(int i = 1;i<=n;i++)
	{
		printf("%-5d",sst->elem[i].data);
	}
	printf("\nposition of key i is:\n");
	printf("%d\n",search(sst,3));
	system("pause");
}

  

原文地址:https://www.cnblogs.com/wuliqun/p/2418480.html