栈的基本实现代码

/*栈的结构定义*/
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;
}


posted @ 2017-03-18 10:35  Zhao_Xu_Jie  阅读(345)  评论(0编辑  收藏  举报