//栈的结构定义
//元素下标同数组 从0开始
//***************************
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXSIZE 1000
#define MAX_SIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
//***************************
typedef int Status;//Status是函数的类型,其值是函数结果的状态代码
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType data[MAXSIZE];
int top;//用于栈顶指针
}SqStack;
//进栈操作
Status Push(SqStack* S, SElemType e)
{
if (S->top == MAXSIZE - 1)//看栈是否满
//解释:MAXSIZE为栈里面可用存的最多数据个数例 100,顶栈的元素下标就是99
{
return ERROR;
}
S->top++;//顶栈的指针增加1
S->data[S->top] = e;//将新插入元素赋值给顶栈空间
return OK;
}
//出栈操作
//若栈不空,则删除S的顶栈元素,用e返回其值,并返回OK,否则返回ERROR
Status Pop(SqStack* S, SElemType* e)
{
if (S->top == -1)
{
return ERROR;
}
*e = S->data[S->top];//将要删除的顶栈元素赋值给e
S->top--;//顶栈指针减1
return OK;
}
//两栈共享空间结构
typedef struct
{
SElemType data[MAXSIZE];
int top1;//栈1栈顶指针
int top2;//栈2栈顶指针
}SqDoubleStack;
//判断是栈1还是栈2的元素
//进栈
Status Push(SqDoubleStack* S, SElemType e, int stackNumber)
{
if (S->top1 + 1 == S->top2)//栈已满 不能再进入新元素了
{
return ERROR;
}
if (stackNumber == 1)//栈1有元素进栈
{
S->data[++S->top1] = e;//如果栈1则先top1+1后给数组元素赋值
}
else if (stackNumber == 2)//栈2有元素进栈
{
S->data[--S->top2] == e;//若栈2则先top2-1后给数组元素赋值
}
return OK;
}
//出栈
Status Pop(SqDoubleStack* S, SElemType* e, int stackNumber)
{
if (stackNumber == 1)
{
if (S->top1 == -1)
{
return ERROR;//栈1空栈 溢出
}
*e = S->data[S->top1--];//将栈1的栈顶元素出栈
}
else if (stackNumber == 2)
{
if (S->top2 == MAXSIZE)
{
return ERROR;//栈2空栈 溢出
}
*e = S->data[S->top2++];//将栈2的栈顶元素弹出
}
return OK;
}
//栈链
typedef struct StackNode
{
SElemType data;
struct StackNode* next;
}StackNode, *LinkStackPtr;
typedef struct LinkStack
{
LinkStackPtr top;
int count;
}LinkStack;
//进栈
//插入元素e为新的栈顶元素
Status Push(LinkStack* S, SElemType e)
{
LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
s->data = e;
s->next = S->top;//把当前的栈顶元素赋值给新结点的直接后继
S->top = s;//将新的结点 s赋值给栈顶指针
S->count++;
return OK;
}
//出栈操作
Status Pop(LinkStack* S, SElemType* e)
{
LinkStackPtr p;
if (StackEmpty(*S))
{
return ERROR;
}
*e = S->top->data;
p = S->top;//将栈顶结点赋值给p
S->top = S->top->next;//是的栈顶指针下移一位,指向后一结点
free(p);
S->count--;
return OK;
}
总结