@【数据结构】(顺序表的查找)

@【数据结构】(顺序表的查找)

#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):
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值