#数据结构 Record Two# #Stack 、Queue #
#堆栈#
栈是一个先进后出的线性表,它仅允许在表的一端进行插入和删除操作(运算受限的线性表)!
下面首先来看一看顺序存储实现的堆栈:
/*堆栈的顺序存储实现*/
/*本测试所用数据类型为int型*/
#include <cstdio>
#include <cstdlib>
#define ERROR -1
typedef int Position;
typedef struct SNode *Stack;
struct SNode{
int * Data;
Position Top;
int MaxSize;
};
/*创建一个空栈*/
Stack CreateStack(int MaxSize){
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->Data = (int*)malloc(MaxSize*sizeof(int));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
/*判断栈是否满*/
bool isFull(Stack S){
return (S->Top == S->MaxSize-1);
}
/*入栈操作*/
bool Push(Stack S , int X){
if( isFull(S) ){
printf("堆栈满\n");
return false;
}
else{
S->Data[++(S->Top)] = X;
printf("元素%d入栈成功\n",X);
return true;
}
}
/*判断栈是否为空*/
bool isEmpty(Stack S){
return (S->Top == -1);
}
/*出栈操作*/
int Pop(Stack S){
if( isEmpty(S) ){
printf("堆栈空\n");
return ERROR;
}
else{
return (S->Data[(S->Top)--]);
}
}
int main(){
const int MAXSIZE = 5;
Stack S_stack = CreateStack(MAXSIZE);
Push(S_stack,1);
Push(S_stack,2);
Push(S_stack,3);
Push(S_stack,4);
Push(S_stack