顺序栈基本运算(实验题3.1)

//
//SqStack.h
//顺序栈的基本运算
//2013-10-12 0:06
//

#pragma once

#define MaxSize 5

typedef int ElemType;

typedef struct
{
	ElemType elem[MaxSize];

	int top;  //栈指针
}SqStack;

void InitStack(SqStack* &s);

void ClearStack(SqStack* &s);

int StackLength(SqStack* s);

int StackEmpty(SqStack* s);

int Push(SqStack* &s,ElemType e);  //进栈

int Pop(SqStack* &s,ElemType& e);  //出栈

int GetTop(SqStack* &s,ElemType& e);  //取栈顶元素

void DispStack(SqStack* s);


//SqStack.cpp

#include "SqStack.h"
#include <malloc.h>
#include <stdio.h>

void InitStack( SqStack* &s )
{
	s = (SqStack*)malloc(sizeof(SqStack));
	s->top = -1;
}

void ClearStack( SqStack* &s )
{
	free(s);
}

int StackLength( SqStack* s )
{
	return s->top+1;
}

int StackEmpty( SqStack* s )
{
	return s->top == -1;
}

int Push( SqStack* &s,ElemType e )
{
	if ( s->top >= MaxSize -1)
	{
		return 0;
	}

	s->top ++;
	s->elem[s->top] = e;
	
	return 1;
}

int Pop( SqStack* &s,ElemType& e )
{
	if ( -1 == s->top)
	{
		return 0;
	}
	s->top--;

	return 1;
}

int GetTop( SqStack* &s,ElemType& e )
{
	if ( s->top == -1 || s->top >= MaxSize)
	{
		return 0;
	}

	e = s->elem[s->top];
	return 1;
}

void DispStack( SqStack* s )
{
	if ( s->top == -1 || s->top >= MaxSize)
	{
		return;
	}

	for ( int i = s->top; i >= 0; i --)
	{
		printf("%d,",s->elem[i]);
	}

	printf("\n");
}


 

 

main.cpp

#include "SqStack.h"

int main()
{
	SqStack*s;
	InitStack(s);

	Push(s,1);

	DispStack(s);

	Push(s,2);

	DispStack(s);

	Push(s,3);

	DispStack(s);

	Push(s,4);

	DispStack(s);

	ElemType e;

	Pop(s,e);

	DispStack(s);

	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值