用c语言实现栈

栈是一种后进先出的数据结构,栈有两种存储结构:顺序存储链式存储

栈的顺序存储结构简称为顺序栈

顺序栈的c语言实现:

#define STACKSIZE 100
typedef int DataType;

typedef struct  
{
	DataType data[STACKSIZE];
	int top; //指向栈顶,为-1时,栈中没有元素
}SeqStack;

bool InitStack(SeqStack *pSS)
{
	pSS = (SeqStack *)malloc(sizeof(SeqStack));
	if (pSS == NULL)
		return false;

	pSS->top = -1;
	return true;
}

bool IsEmptyStack(SeqStack *pSS)
{
	if (pSS->top == -1)
		return true;
	else
		return false;
}

bool IsFullStack(SeqStack *pSS)
{
	if (pSS->top == (STACKSIZE - 1))
		return true;
	else
		return false;
}

bool PushElement(SeqStack *pSS, DataType dData)
{
	if (IsFullStack(pSS))
		return false;

	pSS->top++;
	pSS->data[pSS->top] = dData;
	return true;
}

bool PopElement(SeqStack *pSS, DataType *pData)
{
	if (IsEmptyStack(pSS))
		return false;

	*pData = pSS->data[pSS->top];
	pSS->top--;
	return true;
}

bool GetTopElement(SeqStack *pSS, DataType *pData)
{
	if (IsEmptyStack(pSS))
		return false;

	*pData = pSS->data[pSS->top];
	return true;
}


栈的链式存储结构简称为链栈

链栈的c语言实现:

typedef int DataType;

typedef struct node
{
	DataType data;
	struct node *next;
}LinkStack;

bool InitStack(LinkStack *pTop)
{
	pTop = (LinkStack *)malloc(sizeof(LinkStack)); //pTop指向的结点不存放数据,它的下一个结点才是真正的栈顶元素
	if (pTop == NULL)
		return false;

	pTop->next = NULL;
	return true;
}

bool IsEmptyStack(LinkStack *pTop)
{
	if (pTop->next == NULL)
		return true;
	else
		return false;
}

bool PushElement(LinkStack *pTop, DataType dData)
{
	LinkStack *p = NULL;
	p = (LinkStack *)malloc(sizeof(LinkStack));
	if (p == NULL)
		return false;

	p->data = dData;
	p->next = pTop->next;
	pTop->next = p;
	return true;
}

bool PopElement(LinkStack *pTop, DataType *pData)
{
	LinkStack *p;
	if (IsEmptyStack(pTop))
		return false;

	p = pTop->next;
	*pData = p->data;
	pTop->next = p->next;
	free(p);
	return true;
}

bool GetTopElement(LinkStack *pTop, DataType *pData)
{
	if (IsEmptyStack(pTop))
		return false;

	*pData = pTop->next->data;
	return true;
}






©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页