数据结构---栈的顺序实现

栈是一种LIFO表,即后进先出表,可以把栈理解为 火车调度时的情况。先进入一节车厢,记为1,再进入一节车厢,记为2,。1想要出站,必须2先出站。也可以理解为洗盘子的情形,洗完一个盘子后放在最下方,再洗一个放在上一个盘子的上方,最后需要取用盘子的时候就从最上面的一个取。


#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
typedef int ElemType;

typedef struct Stack
{
	ElemType *Base;
	int Length;
}Stack, *PtrStack;

//creat an empty stack
PtrStack InitStack();

//push an element into stack
void Push(PtrStack S, ElemType E);

//Pop an element and return it
ElemType Pop(PtrStack S);

//print elements of stack
void PrintStack(PtrStack S);

int main()
{
	PtrStack S = InitStack();
	Push(S, 1);
	Push(S, 2);
	Push(S, 4);
	Push(S, 3);
	PrintStack(S);
	printf("%d ", Pop(S));
        printf("%d\n", Pop(S));
	PrintStack(S);
	return 0;
}

PtrStack InitStack()
{
	PtrStack S = (PtrStack)malloc(sizeof(Stack));
	S->Base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
	S->Length = 0;
	return S;
}

void Push(PtrStack S, ElemType E)
{
	if(S->Length == STACK_INIT_SIZE)
	{
		printf("Stack is full\n");
		exit(1);
	}
	*(S->Base + S->Length) = E;
	S->Length++;
}

ElemType Pop(PtrStack S)
{
	if(!S->Length)
	{
		printf("Stack is empty\n");
		exit(1);
	}
	S->Length--;
	return *(S->Base + S->Length);
}

void PrintStack(PtrStack S)
{
	for(int i = 0 ; i < S->Length ; i ++)
		printf("%d%c", *(S->Base + i), (i == S->Length - 1) ? '\n' : ' ');
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值