数据结构顺序表操作

该博客展示了如何使用C++实现顺序表的数据结构,包括插入、删除、查找、打印和反转等基本操作。顺序表s1已经初始化并打印其元素。代码中定义了结构体sequenlist,包含了数组vec和最后一个元素的索引last。提供了insert函数进行插入操作,dele函数进行删除,locate函数查找元素位置,inverse函数反转顺序表,order_insert函数按顺序插入元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

#define MAXSIZE 100
#define OK 1
#define OVERFLOW -2

#include<iostream>
using namespace std;

typedef int elemtype;
typedef struct{
	elemtype vec[MAXSIZE];
	int last;
}sequenlist;

void listprint(sequenlist *L)
{
	int i;
	for(i=0;i<=(L->last  );i++)
	{
		cout<<L->vec[i]<<" ";
	}
}

int locate(sequenlist *L,int K)
{
	int i;
	for(i=0;i<=(L->last );i++)
	{
		if(K==(L->vec[i]))
		{
			return i;
		}
	 } 
	 return -1;
}

int insert(sequenlist *L,int i,int x)
{
	int j;
	if((L->last>=MAXSIZE-1))
	{
		cout<<"overflow";
		return 0;
	}
	else
		if(i<=0||i>(L->last+1))
		{	cout<<"error";
		    return 0;
		}
		else{
			for(j=L->last;j>=i-1;j--)
			{
				L->vec[j+1] = L->vec [j];
			}
			L->vec[i-1] = x;
			L->last ++;
		}
	return 1;
}

int dele(sequenlist *L,int i)
{
	if(i<=0||i>(L->last+1))
	{
		cout<<"error";
		return 0;
	}
	else
	{
		for(int j=i;j<=L->last ;j++)
		{
			L->vec[j-1] = L->vec [j];
		}
		L->last --;
	}
	return 1;
}

void inverse(sequenlist *L)
{
	int i = 0,j = L->last ;
	int q = 0;
	while(i<j)
	{
		q = L->vec[i];
		L->vec[i] = L->vec[j];
		L->vec[j] = q;
		i++;
		j--;
	}
}

void order_insert(sequenlist *L,int k)
{
	int i,a;
	for(i=0;i<=L->last;i++)
	{
		if(k<(L->vec [i]))
		{
			a = i;break;
		}
	}
	if(k>L->vec [L->last ])
		a = L->last +1;
	for(i=L->last;i>=a ;i++)
	{
		L->vec [i+1] = L->vec [i];
	}
	L->vec [a] = k;
	L->last ++;
}

int main()
{
	sequenlist s1={{1,3,6,10,15,21,28,36,45},8};
	listprint(&s1);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值