共享栈

来源:互联网 发布:矩阵防御 app 编辑:程序博客网 时间:2024/05/21 18:40

1、算法思想

两个栈共用一个存储空间,由于栈底不动,所以设置在数组的两端。

2、代码

#include<iostream>using namespace std;#define ok 1#define no 0#define error 0#define yes 1#define maxsize 50struct sharestack//定义共享栈{    int data[maxsize];    int top1, top2;};int initstack(sharestack &s)//栈顶指针指向当前栈顶元素,因此进站需要先移动指针,后进元素,出栈要先取元素,后移动指针{    s.top1 = -1;    s.top2 = maxsize;    return ok;}int push(sharestack &s, int st_no, int e)//进栈判满{    if (s.top1 + 1 >= s.top2)        return error;    if (st_no == 1)    {        s.data[++s.top1] = e;        return ok;    }    else     {        s.data[--s.top2] = e;        return ok;    }}int pop(sharestack &s, int st_no, int &e)//出栈判空{    if (st_no == 1)    {        if (s.top1 == -1)            return error;        e = s.data[s.top1--];        return ok;    }    else    {        if (s.top2== maxsize)            return error;        e = s.data[s.top2++];        return ok;    }}int isempty(sharestack s, int st_no)//判空函数{    if (st_no == 1)    {        if (s.top1 == -1)            return yes;        else        return no;    }    else    {        if (s.top2 == maxsize)            return yes;        else            return no;    }}int isfull(sharestack s, int st_no)//判满函数{    if (s.top1 + 1 >= s.top2)        return yes;    else        return no;}int gettop(sharestack s, int st_no, int &e)//取栈顶元素{    if (st_no == 1)    {        if (s.top1 == -1)            return error;        e = s.data[s.top1];        return ok;    }    else    {        if (s.top2 == maxsize)            return error;        e = s.data[s.top2];        return ok;    }}void main(){    int i;    sharestack s;    initstack(s);    for (i = 1; i <= 20; i++)        push(s, 1, i);    for (i = 50; i >= 20; i--)        push(s, 2, i);    while (!isempty(s, 1))    {        pop(s, 1, i);        cout << i << "  ";    }    cout << endl;    while (!isempty(s, 2))    {        pop(s, 2, i);        cout << i << "  ";    }}
0 0
原创粉丝点击