顺序表:在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构。线性表采用顺序存储的方式存储就称之为顺序表。顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中。
#pragma once //防止头文件多次被引用
#denfine SIZE 10
typedef struct SeqList
{
int elem[SIZE];
int usedsize;//有效的数据长度
}SeqList,*PSeqList;
void InitSeqList(PSeqList ps);//初始化顺序表
static bool isFull(PSeqList ps);
bool Insert(PSeqList ps,int pos,int val);
int Seach(PSeqList ps,int pos,int key);//查找pos 位置的key值
bool DeletePos(PSeqList ps,int pos,int *rtv);//删除pos位置的值,并保存到rtv,位置固定
bool Delete(PSeqList ps,int pos,int key);//删除从pos位置开始查找的key值,位置不固定
bool GetElem(PSeqList ps,int pos,int *rtv);//获取pos 位置的值,并保存到rtv;
bool Clear(PSeqList ps);//清除
bool Destroy(PSeqList ps);//毁坏
int GetLength(PSeqList ps);//获取表的有效长度
void Show(PSeqList ps);//输出顺序表
#include<stdio.h>
#include"SeqList.h"
#include<assert.h>
void InitSeqList(PSeqList ps)
{
assert(ps != NULL);
if(ps = NULL)
{
return;
}
ps->usedsize = 0;
}
static bool isFull(PSeqList ps)
{
assert(ps != NULL);
return ps->usedsize == SIZE;
}
bool Insert(PSeqList ps,int pos,int val)
{
assert( ps != NULL);
if(pos < 0 || pos > ps->usedsize || isFull(ps))
{
return false;
}
for(int i = ps->usedsize-1;i >= pos;i--)
{
ps->elem[i+1] = ps->elem[i];
}
ps->elem[pos] = val;
ps->usedsize++;
return true;
}
int Seach(PSeqList ps,int pos,int key)
{
assert(ps != NULL);
if(pos < 0 || pos >= ps->usedsize)
{
return -1;
}
for(int i = pos;i < ps-> usedsize;i++)
{
if(ps->elem[i] == key)
{
return i;
}
}
return -1;
}
bool DeletePos(PSeqList ps,int pos,int *rtv)
{
assert(ps != NULL);
if(pos < 0 || pos >= ps->usedsize)
{
return false;
}
if(rtv != NULL)
{
*rtv = ps->elem[pos];
}
for(int i = pos; i< ps->usedsize-1;i++)
{
ps->elem[i] = ps->elem[i+1];
}
ps->usedsize--;
return true;
}
bool Delete(PSeqList ps,int pos,int key)
{
assert(ps != NULL);
if(pos <0 || pos >= ps->usedasize)
{
return fasle;
}
int tmp = Search(ps,0,key);
if(tmp < 0)
{
return false;
}
return DeletePos(ps,tmp,NULL);
}
bool GetElem(PSeqList ps,int pos,int *rtv)
{
assert(ps != NULL);
if(pos < 0 || pos >= ps->usedsize)
{
return false;
}
if( rtv != NULL)
{
*rtv = ps->elem[pos];
}
return true;
}
bool Clear(PSeqList ps)
{
ps->usedsize = 0;
return true;
}
bool Destroy(PSeqList ps)
{
Clear(ps);
retrun true;
}
int GetLength(PSeqList ps)
{
assert(ps != NULL);
return ps->usedsize;
}
void Show(PSeqList ps)
{
assert(ps != NULL);
for(int i = 0;i < ps->usedsize ;i++)
{
printf("%d ",ps->elem[i]);
}
printf("\n");
}
实现 :
#include<stdio.h>
#include"SeqList.h"
int main()
{
SeqList ps;
InitSeqList(&ps);
Insert(&ps,0,20);
Insert(&ps,1,10);
Insert(&ps,2,5);
Insert(&ps,3,32);
Insert(&ps,4,35);
Insert(&ps,5,64);
Insert(&ps,6,54);
Insert(&ps,7,25);
Show(&ps);
int tmp = 0;
//DeletePos(&ps,5,&tmp);
GetElem(&ps,3,&tmp);
printf("%d\n",tmp);
/*int tmp = GetLength(&ps);
printf("%d\n ",tmp);
Delete(&ps,5,5);
int tmp2 = GetLength(&ps);
printf("%d\n ",tmp2);*/
Show(&ps);
return 0;
}

234

被折叠的 条评论
为什么被折叠?



