栈和队列的操作

#include <bits/stdc++.h>
#define Status int
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
using namespace std;
typedef struct{
    int *base;
    int *top;
    int stacksize;
}SqStack;
Status InitStack(SqStack &S)
{
    S.base=(int*)malloc(STACK_INIT_SIZE*sizeof (int));
    if(!S.base) exit(-2);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return 1;
}
Status GetTop(SqStack S,int &e)
{
    if(S.top==S.base) return 0;
    e=*(S.top-1);
    return 1;
}
Status Push(SqStack &S,int e)
{
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(int*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int));
        if(!S.base)exit(-2);
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }
    *S.top++=e;
    return 1;
}
Status Pop(SqStack &S,int &e)
{
    if(S.top==S.base) return 0;
    e=*--S.top;
    return 1;
}

typedef struct QNode
{

    int data;
    struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
    QueuePtr front;
    QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue &Q)
{
    Q.front=Q.rear=(QueuePtr)malloc(sizeof (QNode));
    if(!Q.front) exit(-2);
    Q.front->next=NULL;
    return 1;
}
Status DestroyQueue(LinkQueue &Q)
{
    while(Q.front)
    {

        Q.rear=Q.front->next;
        free(Q.front);
        Q.front=Q.rear;
    }
    return 1;
}
Status EnQueue(LinkQueue &Q,int e)
{
    QueuePtr p=(QueuePtr)malloc(sizeof (QNode));
    if(!p) exit(-2);
    p->data=e;p->next=NULL;
    Q.rear->next=p;
    Q.rear=p;
    return 1;
}
Status DeQueue(LinkQueue &Q,int &e)
{
    QueuePtr p;
    if(Q.front==Q.rear) return 0;
    p=Q.front->next;
    e=p->data;
    Q.front->next=p->next;
    if(Q.rear==p) Q.rear=Q.front;
    free(p);
    return 1;
}
int main()
{
    SqStack S;
    LinkQueue Q;
    InitStack(S);
    int e1=100,e2=101,d,e3;
    Push(S,e1);
    Push(S,e2);
    GetTop(S,d);
    cout<<d<<endl;
    Pop(S,d);
    cout<<d<<endl;
    GetTop(S,d);
    cout<<d<<endl;
    InitQueue(Q);
    EnQueue(Q,d);
    DeQueue(Q,e3);
    cout<<e3<<endl;
    return 0;
}
posted @ 2018-04-18 10:19  ffgcc  阅读(207)  评论(0编辑  收藏  举报