SqHeader.h

#ifndef SQHEADER_H_INCLUDED
#define SQHEADER_H_INCLUDED


//顺序表的存储结构
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType date[MaxSize];
int length;

}SqList;


#endif // SQHEADER_H_INCLUDED

SqList.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "sqHeader.h"
using namespace std;

//建立顺序表
void CreateList(SqList *&L,ElemType a[],int n)
{//方法是将给定的含有n个元素的数组的每个元素依稀放入到顺序表中,并将n赋给顺序表的长度域
int i;
L=(SqList *)malloc(sizeof(SqList));
for(i=0;i<n;i++)
{
L->date[i]=a[i];
}
L->length=n;
}

//初始化线性表
void InitList(SqList *&L)
{
L=(SqList *)malloc(sizeof(SqList));//分配存放线性表的空间
L->length = 0;
}

//销毁线性表
void DestroyList(SqList *&L)
{
free(L);
}

//判断线性表是否为空
bool ListEmpty(SqList *&L)
{
return (L->length==0);
}

//求线性表的长度
int ListLength(SqList *&L)
{
return L->length;
}

//输出线性表
void DisplayList(SqList *&L)
{
int i;
for(i=0;i<L->length;i++)
{
printf("%c ",L->date[i]);
}
printf("\n");
}

//求线性表中某个元素的值
bool GetElem(SqList *L,int i,ElemType &e)
{//该方法用e返回L中第i个元素的值
if(i<1||i>L->length)
return false;
e=L->date[i-1];
return true;
}

//按元素之查找
int LocateElem(SqList *L,ElemType e)
{//该方法在L中从第一个元素开始查找与e相等元素的逻辑ixuhao,若不存在则返回0
int i=0;
while(i<L->length&&L->date[i]!=e)
i++;
if(i>=L->length)
return 0;
else return i+1;

}

//插入数据元素
bool ListInsert(SqList *&L,int i,ElemType e)
{//该方法在L上第i个位置插入元素e
int j;
if(i<1||i>L->length+1)
return false;
i--; //使i变为物理符号
for(j=L->length;j>i;j--)
{
L->date[j]=L->date[j-1];
}
L->date[i]=e;
L->length++;
return true;
}

//删除数据元素
bool DeleteElem(SqList *&L,int i,ElemType &e)
{
int j;
if(i<1||i>L->length)
return false;
i--; //使i变为物理符号
e=L->date[i];
for(j=i;j<L->length-1;j++)
L->date[j]=L->date[j+1];
L->length--;
return true;
}


int main()
{
SqList *L;
ElemType e;
printf("顺序表的基本运算如下:\n");
printf(" (1)初始化顺序表L\n");
InitList(L);
printf(" (2)依次采用尾插法插入a,b,c,d,e元素\n");
ListInsert(L,1,'a');
ListInsert(L,2,'b');
ListInsert(L,3,'c');
ListInsert(L,4,'d');
ListInsert(L,5,'e');
printf(" (3)输出顺序表L:");
DisplayList(L);
printf(" (4)顺序表L长度=%d\n",ListLength(L));
printf(" (5)顺序表L为%s\n",(ListEmpty(L)?"空":"非空"));
GetElem(L,3,e);
printf(" (6)顺序表L的第3个元素=%c\n",e);
printf(" (7)元素a的位置=%d\n",LocateElem(L,'a'));
printf(" (8)在第4个元素位置上插入f元素\n");
ListInsert(L,4,'f');
printf(" (9)输出顺序表L:");
DisplayList(L);
printf(" (10)删除L的第3个元素\n");
DeleteElem(L,3,e);
printf(" (11)输出顺序表L:");
DisplayList(L);
printf(" (12)释放顺序表L\n");
DestroyList(L);
}

运行结果:

线性表之顺序表基本操作_struct