上一篇文章说的是静态的顺序表,静态顺序表指的是在最开始的时间段就定义了整个表值得长度。然而动态的顺序表指的是先开辟一定空间,当空间占满时,我们再继续接着开辟空间,用来完成数据的存放,逐步开辟空间来进行存放。

    这就是动态顺序表的基本逻辑,我直接上代码,废话不多说了额=。=:

顺序表的重置。我们开辟5个节点空间。

void InitSeqList(SeqList* seq)
{
	assert(seq);
	seq->_arry = (DataType *)malloc(sizeof(DataType)*DEFAUIL_CAPACITY);
	seq->_size = 0;
	seq->_capicity = 5;
}

输出顺序表

void PrintSeqList(SeqList* seq)
{
	size_t index;
	assert(seq);
	for(index = 0;index < seq->_size;index++)
	{
		printf("%d->",seq->_arry[index]);
	}
	printf("->NULL");
}

当当前顺序表满时,接着创建顺序表空间

void CreatLength(SeqList *seq)
{
	assert(seq);
	if(seq->_size == seq->_capicity)
	{
		seq->_capicity *= 2;
		seq->_arry = (DataType *)realloc(seq->_arry,sizeof(DataType)*seq->_capicity);
		if(seq->_arry == NULL)
		{
			printf("MALLOC ERROR");
			exit(0);
		}
	}
}

尾插:

void PushBack(SeqList* seq, DataType x)
{
	assert(seq);
	assert(seq->_arry);
	CreatLength(seq);
	seq->_arry[seq->_size++] = x;
}

插入:

void Insert(SeqList* seq, size_t pos, DataType x)
{
	size_t index;
	assert(seq);
	assert(0<=pos && pos<seq->_size);
	CreatLength(seq);
	for(index = pos;index < seq->_size;++index)
	{
		seq->_arry[pos+1] = seq->_arry[pos];
	}

}

擦除;

void Erase(SeqList* seq, size_t pos)
{
	size_t endIndex;
	assert(seq);
	assert(0<=pos && pos<seq->_size);
	for(endIndex = pos;endIndex < seq->_size-1;endIndex++)
	{
		seq->_arry[endIndex] = seq->_arry[endIndex+1];
	}

}

删除所有:

void RemoveAll(SeqList* seq, DataType x)
{
	size_t OneIndex = 0,TwoIndex = 0;
	int count = 0;
	assert(seq);
	for(;OneIndex < seq->_size;++OneIndex)
	{
		if(seq->_arry[OneIndex] != x)
		{
			seq->_arry[TwoIndex] = seq->_arry[OneIndex];
			TwoIndex++;
		}
		else
		{
			++count;
		}
	}
	seq->_size -= count;
}

这就是顺序表的基本实现,头文件,函数库都没有包含,就说了实现的具体代码。大家可以复制下去看看。