【数据结构】顺序栈的C语言实现(通过顺序表实现栈的顺序存储)

顺序表实现顺序栈的原理

栈是一种特殊的线性表,它只能在线性表的一端进行插入删除操作,允许插入删除的一端称为栈顶,另一端称为栈底。栈的顺序存储即顺序栈是指,用一块连续的内存来存放一个栈,类似于数组,各元素在内存中是一个挨一个的。既然栈也是线性表,那么栈就可以通过线性表来实现,实现顺序栈只需在顺序表的插入删除操作时,只限定在一端操作即可。线性表的顺序存储文章链接如下

【数据结构】线性表的顺序存储API及实现https://blog.csdn.net/qq_43471489/article/details/123762070?spm=1001.2014.3001.5501线性表可以在头部和尾部进行插入删除,而栈只能在栈顶进行插入删除,那么应该选择顺序表的哪一端作为栈顶呢?

 假如线性表头部作为栈顶,如上图所示,也就是说线性表的0号位置处作为栈顶,那么每次插入删除,都需要后面的元素都后移或前移(在0号位置插入时,需要原来的0号变为1号,原来的1号变为2号,以此类推,每个元素都要往后移动一位;删除0号元素时,0号位置空出,应把1号前移变为0号,2号前移变为1号,每个元素都要前移一位),会造成大量的数据移动。所以,应选择线性表的尾部作为栈顶,这样插入删除都不要其他元素移动。

顺序栈的API

typedef void SequenceStack;
typedef void SequenceStackNode;

SequenceStack* SequenceStack_Create(int capacity);

void SequenceStack_Destroy(SequenceStack* stack);

void SequenceStack_Clear(SequenceStack* stack);

int SequenceStack_Push(SequenceStack* stack, SequenceStackNode* node);

SequenceStackNode* SequenceStack_Top(SequenceStack* stack);

SequenceStackNode* SequenceStack_Pop(SequenceStack* stack);

int SequenceStack_Size(SequenceStack* stack);

顺序栈的API实现

SequenceStack* SequenceStack_Create(int capacity)
{
	SequenceStack* pTemp = NULL;
	pTemp = (SequenceStack*)LinearList_Create(capacity);
	if (pTemp == NULL)
	{
		printf("LinearList_Create() err\n");
		return NULL;
	}
	return pTemp;
}

void SequenceStack_Destroy(SequenceStack* stack)
{
	LinearList_Destroy((LinearList*)stack);
}

void SequenceStack_Clear(SequenceStack* stack)
{
	LinearList_Clear((LinearList*)stack);
}

int SequenceStack_Push(SequenceStack* stack, SequenceStackNode* node)
{
	return LinearList_Insert((LinearList*)stack, node, LinearList_Length((LinearList*)stack));
}

SequenceStackNode* SequenceStack_Top(SequenceStack* stack)
{
	return (SequenceStackNode*)LinearList_Get((LinearList*)stack, LinearList_Length((LinearList*)stack) - 1);
}

SequenceStackNode* SequenceStack_Pop(SequenceStack* stack)
{
	return (SequenceStackNode*)LinearList_Delete((LinearList*)stack, LinearList_Length((LinearList*)stack) - 1);
}

int SequenceStack_Size(SequenceStack* stack)
{
	return LinearList_Length((LinearList*)stack);
}

代码资源已经上传

顺序栈的C语言实现(栈的顺序存储)https://download.csdn.net/download/qq_43471489/85066042

posted @ 2022-04-02 11:15  Mindtechnist  阅读(34)  评论(0编辑  收藏  举报  来源