@【数据结构】(顺序表的查找)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
using namespace std;
typedef struct
{
int data[MAX];
int last;
}List;
List *INIT()
{
List *L;
L =(List*)malloc(sizeof(List));
L->last = 0;
return L;
}
void insert(List *&L,int i,int x)
{
int j;
if (L->last == MAX - 1)
cout << "表满" << endl;
if (i<1 || i>L->last + 2)
cout << "位置输入错误" << endl;
for (j = L->last; j > i; j--) //位置i后的元素后移一位
L->data[j] = L->data[j - 1];
L->data[i - 1] = x;
L->last++;
}
void out(List *L)
{
int i;
for (i = 0; i < L->last; i++)
cout << L->data[i] << " ";
cout << endl;
}
int location(List *L, int x)
{
int i = 0;
while (i <= L->last&&L->data[i] != x)
i++;
if (i > L->last)
return -1;
else return i;
}
void main()
{
List *L;
L = INIT();
insert(L, 1, 3); insert(L, 2, 2);
insert(L, 3, 7); insert(L, 4, 9); insert(L, 5, 4);
cout << "顺序表为:";
out(L);
cout << "请输入要查找的元素:";
int x;
cin >> x;
cout << "元素位置为(从0开始计):" <<location(L,x)<< endl;
system("pause");
}
测试(若要位置从0开始,location函数中,返回值为i+1):