#include<stdio.h>
#define KeyType int
#define OtherType int
#define List_size 100
typedef struct{KeyType key;OtherType other;
}RecordType;
typedef struct{RecordType r[List_size];int length;
}Recordlist;
int SeqSearch(Recordlist l,int k)//没有设置监视哨
{
int i=l.length;
while(i>=1&&l.r[i].key!=k)
i--;
if(i>=1)
return(i);
else
return (0);
}
int main(void)
{int i,x;Recordlist L;for(i=0;i<10;i++){printf("请输入顺序表中元素个数:\n"); scanf("%d",&L.length);printf("请输入顺序表中数据:\n"); for(i=1;i<=L.length;i++)scanf("%d",&L.r[i].key);printf("请输入查找的元素\n");scanf("%d",&x);i=SeqSearch(L,x);if(i!=0) printf("查找结果为第%d个数\n",i); elseprintf("查找失败!\n");}return 0;
}
#include<stdio.h>
#define List_size 100
typedef struct{int key;int other;
}RecordType;
typedef struct{RecordType r[List_size];int length;
}Recordlist;
int SeqSearch(Recordlist *L,KeyType x)//设置监视哨
{L->r[0].key=x;int i=L->length ;while(L->r[i].key!=x)i--;return i;
}
int main(void)
{int i,x;Recordlist L,*p=&L;for(i=0;i<10;i++){printf("请输入顺序表中元素个数:\n"); scanf("%d",&L.length);printf("请输入顺序表中数据:\n"); for(i=1;i<=L.length;i++)scanf("%d",&L.r[i].key);printf("请输入查找的元素\n");scanf("%d",&x);i=SeqSearch(p,x);if(i!=0) printf("查找结果为第%d个数\n",i); elseprintf("查找失败!\n");}return 0;
}
l.r[0]为“监视哨”,可以防止越界的作用,也可以提高查找效率。