栈的基本实现代码
Posted 醉卧何处
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈的基本实现代码相关的知识,希望对你有一定的参考价值。
/*栈的结构定义*/
typedef int SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
//进栈
Status Push(SqStack *S,SElemType e)
{
if(S->top == MAXSIZE - 1)
{
return ERROR;
}
S -> top++;
S -> data[S->top] = e;
return OK;
}
//出栈
Status Pop(SqStack *S,SElemType *e)
{
if(S->top == -1)
return ERROR;
*e = S->data[S->top];
S->top++;
return OK;
}
//两栈共享空间结构
typedef struct
{
SElemType data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
//插入元素e为新的栈顶元素
Status Push(SqDoubleStack *S,SElemType e,int stackNumber)
{
if(s->top1 + 1 == s->top2)
return ERROR;
if(stackNumber == 1)
S->data[++s->top1] = e;
if(stackNumber == 2)
S-data[--S->top2] == e;
return OK;
}
//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK,否则返回ERROR
Status Pop(SqDoubleStack *S,SElemType *e,int stackNumber)
{
if(stackNumber == 1)
{
if(S->top1 == -1)
return ERROR;
*e = S->data[S->top1--];
}
else if(stackNumber ==2 )
{
if(S->top2 == MAXSIZE)
return ERROR;
*e = S->data[S->top2++];
}
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)
{
LinkStack s = (LinkStackPtr) malloc (sizeof(StackNode))
s->data = e;
s->next = S-top;
S->top = s;
S->count ++;
return OK;
}
//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK,否则返回ERROR
Status Pop(LinkStack *S,SElemType *e)
{
LinkStack P;
if(StackEmpty(*s))
return ERROR;
*e = S->top->data;
p->S-top;
S-top = S-top->next;
free(p);
S->count--;
return OK;
}
以上是关于栈的基本实现代码的主要内容,如果未能解决你的问题,请参考以下文章