用两个栈来模拟一个队列

#include "stack.h"
#include <stdlib.h>
#include <stdio.h>

int EnQueue(Stack *_push, int *_d)
{
    if(FullStack(_push) == 0)
        return -1;

    PushStack(_push, _d);
}

int DeQueue(Stack *_push, Stack *_pop, int *_d)
{
    int temp = 0;

    if(EmptyStack(_pop) == 0)
    {
        while(EmptyStack(_push) == -1)
        {
            PopStack(_push, &temp);
            PushStack(_pop, &temp);
        }
    }
    PopStack(_pop, _d);
}

#if 1
int main(void)
{
    Stack SPush;
    Stack SPop;
    int i=10, j=20, k=30, m=0, n=0;

    InitStack(&SPush);
    InitStack(&SPop);
    
    EnQueue(&SPush, &i);
    EnQueue(&SPush, &j);
    EnQueue(&SPush, &k);
    
    DeQueue(&SPush, &SPop, &k);
    DeQueue(&SPush, &SPop, &j);
    DeQueue(&SPush, &SPop, &i);

    printf("%d  %d  %d\n", k, j, i);

    exit(0);
}
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"

const int NUM = 10;
const int INCREMENT = 20;

//static int EmptyStack(Stack *_s);
//static int FullStack(Stack *_s);
//static int InitStack(Stack **_s);
//static int PushStack(Stack *_s, int *_d);
//static int PopStack(Stack *_s, int *_d);

int InitStack(Stack *_s)
{
    (_s)->pBase = (int *)malloc(sizeof(int) * NUM);
    if((_s)->pBase == NULL)
        return -1;
    memset((_s)->pBase, '\0', sizeof(int)*NUM);

    (_s)->pTop = (_s)->pBase;
    (_s)->stacksize = NUM;

    return 0;
}

int PushStack(Stack *_s, int *_d)
{
    if(FullStack(_s) == 0)
    {
        _s->pBase = (int *)realloc(_s->pBase, (_s->stacksize+INCREMENT)*sizeof(int));
        if(_s->pBase == NULL)
            return -1;
        _s->pTop = _s->pBase + _s->stacksize;   
        _s->stacksize += INCREMENT;
    }

    *(_s->pTop) = *_d;
    _s->pTop++;
    
    return 0;
}

int PopStack(Stack *_s, int *_d)
{
    if(EmptyStack(_s) == 0)
        return -1;
    
    *_d = *(--(_s->pTop));
}

int EmptyStack(Stack *_s)
{
    if(_s->pTop == _s->pBase)
        return 0;
    else
        return -1;
}

int FullStack(Stack *_s)
{
    if(_s->pTop == (_s->pBase + NUM))
        return 0;
    else
        return -1;
}

#if 0
int main(void)
{
    Stack s;
    int i=10, j=20, k=40, m=0;

    InitStack(&s);
    PushStack(&s, &i);
    PushStack(&s, &j);
    PushStack(&s, &k);
    PopStack(&s,  &i);
    PopStack(&s,  &j);
    PopStack(&s,  &k);
    printf("%d  %d  %d\n", i, j, k);
    exit(0);
}
#endif
#ifndef _STACK_H
#define _STACK_H

#include <stdlib.h>

typedef struct SNOde
{
    int *pTop;
    int *pBase;
    int stacksize;
}SNOde, Stack;

int EmptyStack(Stack *_s);
int FullStack(Stack *_s);
int InitStack(Stack *_s);
int PushStack(Stack *_s, int *_d);
int PopStack(Stack *_s, int *_d);

#endif

 

posted on 2018-05-18 15:29  MrRS  阅读(221)  评论(0编辑  收藏  举报

导航