不定长顺序表

不定长顺序表

与定长顺序表相比最大的特点就是可扩容

代码

DSeqList.h

#define INITSIZE 5
typedef int ELEM_TYPE;
typedef struct DseqList
{
	ELEM_TYPE* parr;
	int cursize;
	int totalsize;
}DseqList,*PDseqList;

void Init(PDseqList pl);
static void resize(PDseqList pl);
bool Insert(PDseqList pl,int pos,ELEM_TYPE val);
void Show(PDseqList pl);
bool IsFull(PDseqList pl);
int DeletePos(PDseqList pl, int pos);
bool DeleteKey(PDseqList pl,ELEM_TYPE key);
int Search(PDseqList pl,ELEM_TYPE key);

 DSeqList.cpp

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include "DSeqList.h"

void Init(PDseqList pl)
{
	if(pl == NULL)
	{
		return ;
	}
	pl->parr = (ELEM_TYPE*)malloc(sizeof(ELEM_TYPE) * INITSIZE);
	assert(pl->parr != NULL);
	pl->cursize = 0;
	pl->totalsize = INITSIZE;
}

static void resize(PDseqList pl)
{
	ELEM_TYPE* newpar = (ELEM_TYPE*)malloc(sizeof(ELEM_TYPE)*(pl->totalsize + INITSIZE));
	assert(newpar != NULL);
	memcpy(newpar,pl->parr,sizeof(pl->parr));
	free(pl->parr);
	pl->parr = newpar;
	pl->totalsize += INITSIZE;
}

bool Insert(PDseqList pl,int pos,ELEM_TYPE val)
{
	if(pl == NULL)
	{
		return false;
	}
	if(pos<0 || pos>pl->cursize)
	{
		return false;
	}
	if(IsFull(pl))
	{
		resize(pl);
	}
	for(int i = pl->cursize; i>=pos; i--)
	{
		pl->parr[i] = pl->parr[i-1];
	}
	pl->parr[pos] = val;
	pl->cursize++;
	return true;
}

int DeletePos(PDseqList pl, int pos)
{
	if(pl == NULL)
	{
		return 0;
	}
	if(pos < 0 || pos > pl->cursize-1)
	{
		return -1;
	}
	if(IsFull(pl))
	{
		resize(pl);
	}
	
	for(int i = pos; i < pl->cursize - 1; i++)
	{
		pl->parr[i] = pl->parr[i+1];
	}
	pl->cursize--;
	pl->totalsize--;
	return 1;
}

bool DeleteKey(PDseqList pl,ELEM_TYPE key)
{
	if(pl == NULL)
	{
		return false;
	}
	int index = Search(pl,key);
	if(index < 0)
	{
		return false;
	}
	for(int i=0 ; i<pl->cursize ; i++)
	{ 
		int j = 0;
		if(pl->parr[i] == key)
		{
			for(j=i; j < pl->cursize-1 ; j++)
			{
				pl->parr[j] = pl->parr[j+1];
				
			}
			pl->cursize--;
			j--;    //因为是边查找边删除,所以要j--
		}
	}
	return true;
}

int Search(PDseqList pl,ELEM_TYPE key)
{
	assert(pl ->parr != NULL);
	int rt = -1;
	for(int i=0; i<pl->cursize ;i++)
	{
		if(pl->parr[i] == key)
		{
			rt = i;
			break;
		}
	}
	return rt;
}

bool IsFull(PDseqList pl)
{
	return pl->totalsize == INITSIZE;
}

void Show(PDseqList pl)
{
	if(pl == NULL)
	{
		return ;
	}
	for(int i = 0; i < pl->cursize ; i++)
	{
		printf("%d ",pl->parr[i]);
	}
	printf("\n");
}

main.cpp

#include <stdio.h>

#include "DSeqList.h"

int main()
{
	DseqList pl;
	Init(&pl);
	for(int i=0; i<9; i++)
	{
		Insert(&pl,i,10+i);
	}
	Insert(&pl,2,1);
	Insert(&pl,4,1);
	//DeletePos(&pl,2);
	DeleteKey(&pl,11);
	Show(&pl);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值