编译软件: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);
}
结果: