靜態棧抽象數據類型stack實現

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

#define MAX_STACK_SIZE 10 //堆棧的最大大小

typedef struct
{
	int key;
	//其餘內容
}Element;
//模板類型


void push( Element item, Element *stack, short *top);
//向堆棧壓入,入棧.成功返回1失敗返回0
Element pop( Element *stack, short *top);
//堆棧的彈出,出棧.成功返回被彈出的數據.失敗報錯
bool IsEmpty( short top);
//檢查堆棧是否爲空,空返回1,不空返回0
bool IsFull( short top);
//檢查堆棧是否滿了,滿返回1,未滿返回0
void stackEmpty(void);
//報告堆棧未空
void stackFull(void);
//報告堆棧已滿

int main(void)
{
	Element A;
	A.key=1;
	Element stack[MAX_STACK_SIZE];
	short top=-1;
    //指向棧頂元素,-1表示空棧
    
    for(int i=0; i<MAX_STACK_SIZE; i++)
	{
		push(A, stack, &top);
		A.key+=1;
		//將A壓入stack
		printf("%d ",stack[top].key);
	}
	putchar('\n');
	for(int i=0; i<MAX_STACK_SIZE; i++)
	{
		printf("%d ",pop(stack, &top).key);
		//stack出棧從棧頂開始
	}
	putchar('\n');
    
	return 0;
}
void push( Element item, Element *stack, short *top)
{
	//將item壓入stack堆棧
	if(IsFull(*top))
		stackFull();
	stack[++(*top)] = item;
}
Element pop( Element *stack, short *top)
{
	if(IsEmpty(*top))
		stackEmpty();
	return stack[(*top)--];
}
bool IsEmpty( short top)
{
	if(top == -1)
		return true;
	else
		return false;
}
bool IsFull( short top)
{
	if(top == MAX_STACK_SIZE-1)
		return true;
	else
	    return false;
}
void stackEmpty(void)
{
	printf("Stack is Empty, cannot pop element\n");
	exit(EXIT_FAILURE);
}
void stackFull(void)
{
	printf("Stack is Full, cannot add element\n");
	exit(EXIT_FAILURE);
}
相關文章
相關標籤/搜索