数据结构学习之栈和栈的操作源码

本文介绍了一种使用一维数组实现的顺序栈数据结构。文章详细解释了栈的基本操作,如初始化、压栈、弹栈等,并通过具体示例展示了如何在C语言中实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用一维数组模拟的顺序栈:
 
#include "declear.h"
#include "stdio.h"

#define MAXSIZE 10

typedef struct  
{
	SElemType data[MAXSIZE];
	int top;
}SqStack;


Status InitStack(SqStack *S)
{
	S->top = -1;
	return OK;
}

Status Visit(SElemType elem)
{
	printf("%d\n",elem);
	return OK;
}

Status StackTraverse(SqStack S)
{
	int index = 0;
	while (index <= S.top)
	{
		Visit(S.data[index]);
		++index;
	}
	//printf("\n");
	return OK;
}

Status Push(SqStack *S, SElemType e)
{
	if (S->top == MAXSIZE - 1)
	{
		return ERROR;
	}

	++S->top;
	S->data[S->top] = e;

	return OK;
}

Status Pop(SqStack *S, SElemType *e)
{
	if (S->top == -1)
	{
		return ERROR;
	}
	
	*e = S->data[S->top];
	--S->top;

	return OK;
}

Status ClearStack(SqStack *S) 
{
	(*S).top = -1;
	return OK;
}

int StackLength(SqStack S)
{
	return S.top + 1;
}

Status GetTop(SqStack S, SElemType *elem)
{
	if (-1 == S.top)
	{
		return ERROR;
	}
	else
	{
		*elem = S.data[S.top];
		return OK;
	}
}

Status EmptyStack(SqStack S)
{
	if (-1 == S.top)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}


int main ()
{
	SqStack stack;
	SElemType elem;

	if (InitStack(&stack) )
	{
		for (int index = 0; index < MAXSIZE; index++)
		{
			Push(&stack, index);
		}
	}

	printf("length = %d\n", StackLength(stack));
	
	printf("The stack is :\n");
	StackTraverse(stack);

	printf("Test of Pop :\n");
	Pop(&stack, &elem);
	printf("elem = %d\n", elem);

	printf("Test of GetTop :\n");
	GetTop(stack, &elem);
	printf("elem = %d\n", elem);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值