【数据结构作业一】写出顺序表的结构体类型定义及查找、插入、删除算法,并以顺序表作存储结构,实现线性表的插入、删除

#include <iostream>
using namespace std;
#define MAXSIZE 50
typedef int ElemType;
typedef struct
{ ElemType  *elem; int length; } SqList;

bool CreateList(SqList &L)
{ int i;
  L.elem=new ElemType[MAXSIZE]; //分配空间
  if (!L.elem)  return false;   
  cout<<"请输入线性表的长度,不能大于"<<MAXSIZE<<':'; cin>>L.length;
  cout<<"请输入表中元素:";
  for(i=0;i<L.length;i++)
     cin>>L.elem[i];   
}

bool ListInsert(SqList &L,int i,ElemType e)
{ if(i<1||i>L.length+1) 
    { cout<<"插入序号错! " ; return  false; }        
  if(L.length==MAXSIZE) 
    { cout<<"表已满! " ;return  false; }   
  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 true;
} 
bool ListDelete(SqList &L,int i)
{
	if((i<1)||(i>L.length))
	{ cout<<"删除序号错! " ; return  false; }
	for(int j=i;j<=L.length-1;j++)
	L.elem[j-1]=L.elem[j];
	--L.length;
	return true;
  }   

void print(SqList L)
{ int i;
  for(i=0;i<L.length;i++)
     if (i==0)  cout<<'('<<L.elem[i];  
     else cout<<','<<L.elem[i];
  cout<<')'<<endl;
}

int main()
{ SqList L; int i,x; ElemType e;
  cout<<"创建[1]"<<endl;
  cout<<"输出[2]"<<endl;
  cout<<"插入[3]"<<endl;
  cout<<"删除[4]"<<endl;
  cout<<"退出[0]"<<endl;
  cout<<"请输入你的选择:";
  cin>>x;
  while(x)
    {  switch(x)
       { case 1:CreateList(L); break;
         case 2:print(L);break;
         case 3:cout<<"请输入插入位置和待插入元素:";   cin>>i>>e;
                ListInsert(L,i,e) ; 
                break;
         case 4:cout<<"请输入删除位置:"; cin>>i;
                ListDelete(L,i);
				break; 
         case 0:break;
         default:cout<<"你的选择有错,请重新选择!" ; 
	   }
	   cout<<"请输入你的选择:"; cin>>x;
    }	  
  return 0;  
}

  • 23
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值