C語言 棧的表示與實現方法

頭文件
#include<stdio.h>
#include<stdlib.h>
抽象數據類型
typedef struct {
	ElemType data[MaxSize];//數組
	int top;
}SqStack;
初始化棧
void InitStack(SqStack &S)
{
	S.top = -1;//代表棧爲空
}
判斷棧是否爲空
bool StackEmpty(SqStack& S)
{
	if (S.top == -1)
		return true;
	else
		return false;
}
入棧操作
bool Push(SqStack& S, ElemType x) //入棧
{
	if (S.top == MaxSize - 1)
	{
		return false;
	}
	S.data[++S.top] = x;
	return true;
}
出棧操作
bool Pop(SqStack& S, ElemType& x) //出棧
{
	if (-1 == S.top) //說明棧爲空
		return false;
	x = S.data[S.top];
	return true;
}
取棧頂元素
bool GetTop(SqStack& S, ElemType& x)
{
	if (-1 == S.top)
		return false;
	x = S.data[S.top];
	return true;
}
獲得棧中元素個數
int LengthStack(SqStack S)
{
	return ++S.top;
}
打印棧元素(從棧頂到棧尾)
void PrintStack(SqStack& S)
{
	printf("從棧頂到棧底元素分別是:");
	for (int i = S.top; i >= 0; i--)
	{
		printf("%d ", S.data[i]);
	}
	printf("\n");
}

測試代碼
int main()
{
	SqStack S;//先進後出 FILO
	bool flag;
	ElemType m;
	InitStack(S);
	Push(S, 1);
	Push(S, 2);
	Push(S, 3);
	PrintStack(S);
	printf("當前棧元素個數爲:%d\n", LengthStack(S));
	Push(S, 4);
	Push(S, 5);
	printf("當前棧元素個數爲:%d", LengthStack(S));
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章