一个线性表是n个数据元素的有限序列,分为顺序表和链表。顺序表指用一组地址连续的存储单元依次存储线性表的数据元素,即逻辑相邻,物理也相邻;链表指用一组任意的存储单元存储线性表的数据元素,即逻辑相邻物理不相邻。
(1)存在唯一的一个被称作“第一个”的数据元素
(2)存在唯一的一个被称作“最后一个”的数据元素
(3)除第一个外,集合中的每一个数据元素只有一个前驱
(4)除最后一个外,集合中的每一个元素均只有一个后继
顺序表包括定长顺序表和不定长顺序表
对定长顺序表的定义
typedef struct SeqList { int elem[NUM]; int length; }SeqList,*PSeqList;
其结构如下:
elem数组存放数据,length存放有效长度
seqlist.h头文件定义
#pragma once //头文件只允许引用一次 #define NUM 10 //定长顺序表,给定长度10 typedef struct SeqList { int elem[NUM]; int length; }SeqList,*PSeqList; void InitSeqList(PSeqList ps);//初始化 bool Insert(PSeqList ps,int pos,int val);//插入 bool IsEmpty(PSeqList ps);//判空 //rtval输出参数 bool Delete(PSeqList ps,int pos,int *rtval);//删除 bool GetElem(PSeqList ps,int pos,int *rtval);//得到某位元素 bool SetElem(PSeqList ps,int pos,int newval);//改变某位元素 int Search(PSeqList ps,int key);//查找 int GetLength(PSeqList ps);//获取有效数据的个数 void Show(PSeqList ps);//打印 void Destroy(PSeqList ps);//销毁 void Clear(PSeqList ps);//清除
具体实现Seqlist.cpp文件
#include"seqlist.h" #include<stdio.h> #include<assert.h> void InitSeqList(PSeqList ps)//初始化 { assert(ps != NULL); if(ps == NULL) { return ; } ps->length = 0; } static bool IsFull(PSeqList ps)//内部判满 { return ps->length == NUM; } bool Insert(PSeqList ps,int pos,int val)//插入 { assert(ps != NULL); if(ps == NULL || pos>ps->length || pos<0 || IsFull(ps))//pos>ps->length 是因为插入时可以直接插入在顺序表的最后面 { return false; } for(int i = ps->length-1;i>=pos;i--) { ps->elem[i+1]=ps->elem[i]; } ps->elem[pos] = val; ps->length++; return true; } bool IsEmpty(PSeqList ps)//判空 { return ps->length == 0; } //rtval输出参数 bool Delete(PSeqList ps,int pos,int *rtval)//删除 { assert(ps != NULL); if(ps == NULL || pos>=ps->length || pos<0) { return false; } if(rtval!=NULL) { *rtval=ps->elem[pos]; } for(int i = pos;i<ps->length;i++) { ps->elem[i]=ps->elem[i+1]; } ps->length--; return true; } bool GetElem(PSeqList ps,int pos,int *rtval)//得到某位元素 { assert(ps != NULL); if(ps == NULL || pos>ps->length || pos<0) { return false; } *rtval=ps->elem[pos]; return true; } bool SetElem(PSeqList ps,int pos,int newval)//改变某位元素 { assert(ps != NULL); if(ps == NULL || pos>=ps->length || pos<0) { return false; } ps->elem[pos]=newval; return true; } int Search(PSeqList ps,int key)//查找 { assert(ps != NULL); if(ps == NULL) { return -1; } for(int i = 0;i<ps->length;i++) { if(ps->elem[i] = key) { return i; } } return -1; } int GetLength(PSeqList ps)//获取有效数据的个数 { return ps->length; } void Show(PSeqList ps)//打印 { assert(ps != NULL); if(ps == NULL) { return ; } for(int i = 0;i<ps->length;i++) { printf("%d ",ps->elem[i]); } printf("\n"); } void Destroy(PSeqList ps)//销毁 { Clear(ps); } void Clear(PSeqList ps)//清除 { ps->length = 0; }
测试test.cpp文件
#include<stdio.h> #include"seqlist.h" int main() { SeqList p; InitSeqList(&p);//初始化 for(int i = 0;i<10;i++) { Insert(&p,i,i); } Show(&p); Delete(&p,2,NULL); Show(&p); Clear(&p); Destroy(&p); }
最终运行结果如下: