线性表的顺序存储表示和实现
线性表的特点
唯一入口,唯一出口,一个前驱,一个后继
线性表的存储结构
顺序存储、链式存储
线性表的顺序表示
一组地址连续的存储单元依次存储线性表的数据元素
顺序表的查找、删除、插入算法平均时间复杂度为 O ( n ) O(n) O(n)
main.cpp
#include <iostream>
#include "functions.h"
int main(int argc, char** argv) {
SqList L;
char arr[] = "hello";
int i;
char e;
InitList_Sq(L);
for(i=1;i<=5;i++)
{
ListInsert_Sq(L,i,arr[i-1]);
}
printf("插入顺序表内容为:");
for(i=0;i<GetLength(L);i++)
printf("%c",L.elem[i]);
printf("\n");
ListDelete_Sq(L,3,e);
printf("删除第3个内容:%c\n",e);
printf("删除后为:");
for(i=0;i<GetLength(L);i++)
printf("%c",L.elem[i]);
return 0;
}
functions.cpp
#include <iostream>
#include "functions.h"
Status InitList_Sq(SqList &L) //线性表的初始化
{
L.elem = new ElemType[MAXSIZE];
printf("创建顺序表成功!\n");
if(!L.elem) exit(OVERFLOW); //异常处理,分配失败返回-2
L.length = 0;
return OK;
}
void DestoryList(SqList &L) //释放存储空间
{
if(L.elem) delete L.elem;
printf("已删除顺序表!");
}
void ClearList(SqList &L) //线性表长度设为0
{
L.length = 0;
}
int GetLength(SqList L) //求线性表长度
{
return(L.length);
}
int isEmpty(SqList L) //判断是否为空
{
if(L.length==0) return 1;
else return 0;
}
int GetElem(SqList L,int i,ElemType &e)
{
if(i<1||i>L.length) return ERROR;//错误索引
e = L.elem[i-1];
return OK;
}
int LocateElem(SqList L,ElemType e)
{
for(int i=0;i<L.length;i++){
if(L.elem[i]==e) return i+1;
}
return 0;
}
Status ListInsert_Sq(SqList &L,int i,ElemType e)//i表示插入第i个
{
if(i<1||i>L.length+1) return ERROR;
if(L.length==MAXSIZE) return ERROR;
//第i个位置,索引为i-1,最后一个位置为length,索引为length-1
for(int j =L.length;j>=i;j--)
L.elem[j] = L.elem[j-1];
L.elem[i-1] = e;
L.length++;
return OK;
}
Status ListDelete_Sq(SqList &L,int i,ElemType &e)
{
if(i<1||i>=L.length+1) return ERROR;
e = L.elem[i-1];
for(int j =i-1;j<=L.length-1;j++)
{
L.elem[j] = L.elem[j+1];
}
L.length--;
return OK;
}
functions.h
#ifndef __FUNCTIONS_H__
#define __FUNCTIONS_H__
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100
typedef int Status;
typedef char ElemType;
typedef struct //定义线性表型
{
ElemType *elem; //动态分配内存 or 写成数组形式
int length;
}SqList;
Status InitList_Sq(SqList &L);
void DestoryList(SqList &L);
void ClearList(SqList &L);
int GetLength(SqList L);
int isEmpty(SqList L);
int GetElem(SqList L,int i,ElemType &e);
int LocateElem(SqList L,ElemType e);
Status ListInsert_Sq(SqList &L,int i,ElemType e);
Status ListDelete_Sq(SqList &L,int i,ElemType &e);
#endif