# 使用数组实现堆栈

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
#define OK    1
#define ERROR 0
typedef int Status;
typedef int SElemType;
struct SqStack
{
SElemType data[MAXSIZE];//数组实现堆栈
int top;                //栈元素序号
};

Status push(struct SqStack *S, SElemType value)
{
/*栈满*/
if(S->top == MAXSIZE - 1)
{
return ERROR;
}
S->top++;
S->data[S->top] = value;
return OK;
}

Status pop(struct SqStack *S, SElemType *value)
{
/*栈空*/
if(S->top == -1)
return ERROR;
*value = S->data[S->top];
S->top--;
return OK;
}

int is_full(struct SqStack *S)
{
return S->top == MAXSIZE- 1;
}

int is_empty(struct SqStack *S)
{
return S->top == -1;
}

int main(void)
{
struct SqStack *stack = (struct SqStack*)malloc(sizeof(struct SqStack));
int i = 0;
int value;
stack->top = -1;//这句话很重要，不然会出错
for(i=0; i<=10; i++)
{
if(is_full(stack))
{
printf("stack is full\n");
break;
}
push(stack, i);
printf("top is %d\n", stack->data[stack->top]);
}

for(i=0; i<=10; i++)
{
if(is_empty(stack))
{
printf("stack is empty\n");
break;
}
pop(stack, &value);
printf("%d pop\n", value);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
#define OK    1
#define ERROR 0
typedef int Status;
typedef int SElemType;
struct SqStack
{
SElemType data[MAXSIZE];//数组实现堆栈
int top;                //栈元素序号
};

Status push(struct SqStack *S, SElemType value)
{
/*栈满*/
if(S->top == MAXSIZE - 1)
{
return ERROR;
}
S->top++;
S->data[S->top] = value;
return OK;
}

Status pop(struct SqStack *S, SElemType *value)
{
/*栈空*/
if(S->top == -1)
return ERROR;
*value = S->data[S->top];
S->top--;
return OK;
}

int is_full(struct SqStack *S)
{
return S->top == MAXSIZE- 1;
}

int is_empty(struct SqStack *S)
{
return S->top == -1;
}

int main(void)
{
struct SqStack *stack = (struct SqStack*)malloc(sizeof(struct SqStack));
int i = 0;
int value;
stack->top = -1;//这句话很重要，不然会出错
for(i=0; i<=10; i++)
{
if(is_full(stack))
{
printf("stack is full\n");
break;
}
push(stack, i);
printf("top is %d\n", stack->data[stack->top]);
}

for(i=0; i<=10; i++)
{
if(is_empty(stack))
{
printf("stack is empty\n");
break;
}
pop(stack, &value);
printf("%d pop\n", value);
}
return 0;
}

• 本文已收录于以下专栏：

## 使用数组实现栈

//使用数组来实现栈 package 数组实现栈; import java.util.Arrays; interface StackADT { public void push(Obje...

## 4-7 在一个数组中实现两个堆栈 (20分)

4-7 在一个数组中实现两个堆栈 (20分) 本题要求在一个数组中实现两个堆栈。 函数接口定义： Stack CreateStack( int MaxSize ); bool Pus...

## PHP使用数组实现堆栈和队列

• joyksk
• 2017-06-20 11:59
• 1055

## Java用数组实现堆

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)