线性表-顺序结构

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#define MAXSIZE 100
using namespace std;
/*
顺序表 
*/
typedef struct
{
	int * elem;
	int length;	
} SqList;
//初始化 
int InitList(SqList &L)
{
	L.elem = new int[MAXSIZE];
	if(!L.elem)
	{
		return -1;//error
	}
	L.length = 0;
	return 1;
}
//取值
int getElem(SqList &L,int i,int &e)
{
	if(i<1||i>L.length)
	{
		return -1;
	}
	e = L.elem[i-1];
	return 1;
 } 
 //查找
 int locateElem(SqList &L,int e)
 {
 	for(int i=0;i<L.length;i++)
 	{
 		if(L.elem[i]==e)
 		{
 			return i+1;
		 }
	 }
	 return -1;
  } 
  //插入
  int insertList(SqList &L,int i,int e)
  {
  	if(i<1||i>L.length+1)
  	{
  		return -1;
	  }
	  if(L.length==MAXSIZE)
	  {
	  	return -1;
	  }
	  for(int j=L.length-1;j>=i-1;j--)
	  {
	  	L.elem[j+1] = L.elem[j];
	  }
	  L.elem[i-1] = e;
	  ++L.length;
	  return 1;
  }
  //删除
  int delList(SqList &L,int i)
  {
  	if(i<=0||i>=L.length)
  	{
  		return -1;
	  }
	  for(int j=i;j<=L.length-1;j++)
	  {
	  	L.elem[j-1] = L.elem[j];
	  }
	  --L.length;
	  return 1;
   } 
 
int main()
{
	SqList list;
	InitList(list);
	//给list手动赋值 
	for(int i=1;i<11;i++)
	{
		list.elem[i-1] = i;
		list.length++;
	}
	int elem = 0;
	getElem(list,1,elem);
	cout<<"list 取值:"<<elem<<endl;
	cout<<"list 查找:"<<locateElem(list,5)<<endl;
	cout<<"list 插入:"<<insertList(list,3,12)<<endl;
	cout<<"list 删除:"<<delList(list,3)<<endl;
	
	for(int i=0;i<list.length;i++)
	{
		cout<<"遍历i="<<i<<":"<<list.elem[i]<<endl ;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值