順序堆棧的操作實現

#include<stdio.h>
#define MaxStackSize 100

typedef int DataType;
typedef struct  //定義結構體
{
	DataType stack[MaxStackSize];
	int top;
}SeqStack;

void InitStack(SeqStack *s)   //初始化
{
	s->top = 0;
}

int StackNotEmpty(SeqStack s)  //判斷順序堆棧非空否
{
	if(s.top <= 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
int Push(SeqStack *s,int x)     //入棧
{
	if(s->top >= MaxStackSize)
	{
		printf("堆棧已滿,無法插入!\n");
		return 0;
	}
	s->stack[s->top] = x;
	s->top++;
	return 1;
}

int Pop(SeqStack *s,int *x)  //出棧
{
	if(s->top <= 0)
	{
		printf("堆棧已空!\n");
		return 0;
	}
	s->top--;
	*x = s->stack[s->top];
	return 1;
}

int StackTop(SeqStack s,int *x)  //取棧頂元素
{
	if(s.top <= 0)
	{
		printf("堆棧已空無數據元素出棧!\n");
		return 0;
	}
	*x = s.stack[s.top-1];
	return 1;
}
int main()
{
	SeqStack s;
	int x,i;
	InitStack(&s);
	for(i=0;i<10;i++)
	{
		Push(&s,i+1);
	}
	StackTop(s,&x);
	printf("當前棧頂數據元素爲:%d\n",x);
	printf("依次出棧的數據元素序列如下:\n");
	while(StackNotEmpty(s))
	{
		Pop(&s,&x);
		printf("%d  ",x);
	}
	return 0;
}

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