定长的顺序表及基本操作

来源:互联网 发布:网络用语吃鸡什么意思 编辑:程序博客网 时间:2024/05/24 04:39

自带解引用的符号:->、[]

#pragma once //防止头文件被重复引用
//固定长度的顺序表
#define SIZE 10 //顺序表的长度
typedef struct SeqList
{
 int elem[SIZE];//存放数据的数组
 int length;//有效数据的个数
}SeqList,*PSeqList;

1、头文件(seqlist.h)

#pragma once //防止头文件被重复引用//固定长度的顺序表#define SIZE 10 //顺序表的长度typedef struct SeqList{int elem[SIZE];//存放数据的数组int length;//有效数据的个数}SeqList,*PSeqList;//typedef SeqList * PSeqList;//void InitSeqList(SeqList *ps);void InitSeqList(PSeqList ps);bool Insert(PSeqList ps,int pos,int val);int Search(PSeqList ps,int key);bool DeleteVal(PSeqList ps,int key);bool DeletePos(PSeqList ps,int pos);int GetLength(PSeqList ps);bool IsEmpty(PSeqList ps);void Clear(PSeqList ps);void Destroy(PSeqList ps);void Show(PSeqList ps);bool GetElem(PSeqList ps,int pos,int *rtval);


2、源文件(seqlist.cpp)

#include  <stdio.h>#include <assert.h>#include "seqlist.h"void InitSeqList(PSeqList ps)//初始化顺序表{assert(ps->elem != NULL);ps->length = 0;}static bool IsFull(PSeqList ps)//内部函数判满:只在本文件内部有效{assert(ps->elem != NULL);return ps->length == SIZE;}bool Insert(PSeqList ps,int pos,int val)//在固定位置插入新的数据{assert(ps->elem != NULL);if(pos<0 || pos>ps->length || IsFull(ps))//判断不合法的pos值{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;}int Search(PSeqList ps,int key)//查找函数{assert(ps->elem != NULL);for(int i=0;i<ps->length;i++){if(ps->elem[i] == key){return i;}}return -1;}bool DeleteVal(PSeqList ps,int key)//删除函数:确定的数据不固定位置{assert(ps->elem != NULL);int index = Search(ps,key);if(index < 0){return false;}return DeletePos(ps,index);}bool DeletePos(PSeqList ps,int pos)//删除函数:固定的位置{assert(ps->elem != NULL);if(pos<0 || pos>=ps->length){return false;}for(int i=pos;i<ps->length-1;i++){ps->elem[i] = ps->elem[i+1];}ps->length--;return true;}int GetLength(PSeqList ps)//获取有效数据的长度{assert(ps->elem != NULL);return ps->length;}bool IsEmpty(PSeqList ps)//判空函数{assert(ps->elem != NULL);return ps->length == 0;}void Clear(PSeqList ps)//清空函数{ps->length = 0; }void Destroy(PSeqList ps)//摧毁函数{Clear(ps);}void Show(PSeqList ps)//打印顺序表{for(int i=0;i<ps->length;i++){printf("%d ",ps->elem[i]);}printf("\n");}//rtval:输出参数bool GetElem(PSeqList ps,int pos,int *rtval)//返回某个位置的数据值{if(pos<0 || pos>=ps->length){return false;}*rtval = ps->elem[pos];return true;}

 

3、测试源文件(test.cpp)

#include<stdio.h>#include"seqlist.h"int main(){SeqList s;InitSeqList(&s);for(int i = 0;i < 10;i++){Insert(&s,i,i);}Show(&s);printf("%d\n",Search(&s,10));//测试查找函数printf("%d\n",DeleteVal(&s,6));//测试删除数据printf("%d\n",DeletePos(&s,1));//测试删除固定位置的数据的函数printf("%d\n",GetLength(&s));//测试获取长度的函数return 0;}




原创粉丝点击