线性表

#include 
#include 
using namespace std;
//1.定义存储表示  ppt 22页
typedef int ElemType;               //定义ElemType类型为int
# define  LIST_INIT_SIZE   100  // 线性表存储空间的初始分配量
# define   LISTINCREMENT    10  // 线性表存储空间的分配增量

typedef struct                //若后面不再用,可省略结构名
{
    ElemType *elem;         //存储空间基址
    int    length;      //当前表长(特指元素个数)
    int   listsize;     //当前分配的存储容量(以sizeof(ElemType)为单位)
} SqList;
typedef int Status;
Status   InitList_Sq(SqList &L)
{
    //构造一个空的线性表L。
    L.elem = new ElemType[LIST_INIT_SIZE];
    L.length = 0;                    // 空表长度为0
    L.listsize = LIST_INIT_SIZE;  // 初始存储容量
    return   true;
}
//清空线性表
void ClearList(SqList &L)
{
    L.length=0;                //将线性表的长度置为0
}
//判断线性表是否为空
bool IsEmpty(SqList L)
{
    if (L.length==0)
        return true;
    else
        return false;
}
//求线性表长度
int GetLength(SqList L)
{
    return L.length;
}
//获取线性表指定位置元素
Status GetElem(SqList L,int i,ElemType &e)
{
    if (i<1||i>L.length)
        return -1;
    //判断i值是否合理,若不合理,返回ERROR
    e=L.elem[i-1];   //第i-1的单元存储第i个数据
    return true;
}
int PriorElem(SqList L,int i)
{
	 if (i<1||i>L.length)
        return -1;
	return L.elem[i-2];
}
int NextElem(SqList L,int i)
{
	 if (i<1||i>L.length)
        return -1;
	return L.elem[i];
}
Status ListInsert_Sq(SqList &L,int i,ElemType e)
{
    if(i<1 || i>L.length+1)
        return -1;	         //i值不合法
    if (L.length==LIST_INIT_SIZE)//当前存储空间已满,增加分配
    {
        ElemType* newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
        if (!newbase)
            exit(-2); //存储分配失败
        L.elem=newbase;  //新基址
        L.listsize+=LISTINCREMENT; //增加存储容量
    }
    ElemType* q=&(L.elem[i-1]); //q为插入位置
    for (ElemType* p=&L.elem[L.length-1]; p>=q; --p)
        *(p+1)=*p; 	//插入位置之后的元素右移
    *q=e; 		//插入e
    L.length++; 	//表长增1
    return true;
} //ListInsert_Sq
Status ListDelete_Sq(SqList &L,int i,ElemType &e)
{
    if (i<1||i>L.length)
        return -1;	//i值不合法
    ElemType* p=&(L.elem[i-1]); 	//p为被删除元素的位置
    e=*p;			//被删除元素的值赋给e
    ElemType* q=L.elem+L.length-1;	//表尾元素的位置
    for(++p; p<=q; ++p)
        *(p-1)=*p;		//被删除元素之后的元素左移
    --L.length;		
    return true;
}
void Display_List(SqList L)
{
    for(int i=1; i<=L.length;i++)
        cout<>operate_code;
        if(operate_code==1){
            ClearList(L);
        }
        else if(operate_code==2){
            if(IsEmpty(L))
                cout<<"The list is empty."<>i;
            GetElem(L,i,e);
            cout<>i;
			  if(PriorElem(L,i)==-1){
			  	 cout<<"格式错误"<>i;
			  if(NextElem(L,i)==-1){
			  	 cout<<"格式错误"<>e>>i;
            ListInsert_Sq(L,i,e);
        }
        else if(operate_code==8){
            cout<<"请输入要删除元素的位置"<>i;
            ListDelete_Sq(L,i,e);
        }
        else if(operate_code==9){
            cout<<"The element of list are:"<

 

你可能感兴趣的:(数据结构上机课)