线性表顺序存储及操作

本文详细介绍了如何使用C++实现顺序存储的线性表,包括构造、输出、插入、删除和释放等基本操作。代码中展示了如何动态分配内存以适应线性表的增长,并通过一个简单的主程序演示了这些操作的使用。
摘要由CSDN通过智能技术生成

编译软件:VC6.0

头文件:

//一个公用的头文件:基本定义

#include <stdio.h>
#include <iostream.h>
#include <malloc.h>
#include <process.h>
#define  OK 1
#define  ERROR 0
#define  TRUE 1
#define  FALSE 0
#define  OVERFLOW -1

typedef int Status;

//顺序表
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef struct {
ElemType *elem;
int  length;
int  listsize;

}SqList;

//实现基本操作
//构造
Status InitList (SqList &L )
{
int i,n;
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem)return OVERFLOW;
cin>>endl>>Please input data number: ;
cin>>n;
for(i=0;i<n;i++)
        cin>>L.elem[i];
L.length = n;
L.listsize = LIST_INIT_SIZE;
return OK;
}
//输出
void OutputList (SqList L)
{
int i;
printf("\nThe SqList L :\n");
for(i=0;i<L.length;i++)
cout<<"  "<<L.elem[i];
cout<<endl;
}
//插入
Status ListInsert(SqList &L,int i,ElemType e)
{
ElemType *newbase,*p,*q;
if(i < 1 || i>L.length + 1)
return ERROR;
if(L.length >= L.listsize)
{
newbase = (ElemType * )realloc(L.elem,(L.listsize + LISTINCREMENT) *sizeof (ElemType));
if(!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i - 1]);
for(p = &(L.elem[L.length - 1]);p >= q; --p) *(p+1) = *p;
*q = e;
++L.length;
return OK;
}


//删除
Status ListDelete(SqList &L,int i,ElemType &e)
{
ElemType *q,*p;
if(i < 1 || i>L.length + 1)
return ERROR;
p = &(L.elem[i-1]);
e = *p;
q = L.elem + L.length - 1;
for(++p;p<= q;++p)
*(p - 1) = *p;
--L.length;
return OK;
}
//释放
void DestroyList(SqList &L)
{
free(L.elem);
L.elem = NULL;
L.length = 0;
L.listsize = 0;

}

源文件:

#include "01.h"
#include "02.h"
#include "03.h"
void main ()
{
SqList L;
int i,select;
ElemType e;

if(InitList(L)==OVERFLOW)
{
cout<<endl<<"内存溢出,建立失败!";
return ;
}
else
{
cout<<endl<<"建立成功!恭喜你!"<<endl;
OutputList(L);
}

/*---------------------菜单设计--------------------*/
do{
cout<<"\n\n---链表的基本操作---"<<endl;
cout<<"1:显示表内元素"<<endl;
cout<<"2:插入"<<endl;
cout<<"3:删除"<<endl;
cout<<"0:退出"<<endl;
cout<<"请选择您需要的操作:"<<endl;
cin>>select;
switch(select)
{
case 1:
OutputList(L);
break;
case 2:
cout<<endl<<"输入插入位置和值";
cin>>i>>e;
if(ListInsert(L,i,e)==OK)
{
cout<<endl<<"插入成功"<<endl;
OutputList(L);
}
else
cout<<"插入位置不合法,或者内存溢出"<<endl;
break;
case 3:
cout<<endl<<"输入删除位置:";
cin>>i;
if(ListDelete(L,i,e)==OK)
{
cout<<endl<<"删除成功"<<endl;
OutputList(L);
}
else
cout<<"插入位置不合法,或者内存溢出"<<endl;
break;


default:break;
}
}
while(select);
DestroyList(L);

}

结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值