两个栈实现队列-c语言

#include "stdlib.h"  
#include "stdio.h"  
#include "string.h"  
  
/*此代码只体现思路*/  
 
/********************************************************************两个栈实现队列******************************/
typedef unsigned char BOOL;  
#define TRUE 1  
#define FALSE 0   
  
typedef struct _stack  
{  
    int* stack_bottom_ptr;  
    int* stack_top_ptr;  
    int  stacksize;  
}_stack;  
  
  
static _stack* StackInit(int stackSize);
static BOOL Stack_push(_stack* myStack,int dat);
static int Stack_pop(_stack* myStack);
static BOOL StackIsEmpty(_stack* myStack);



_stack*  t_stack1 = NULL;
_stack*  t_stack2 = NULL; 

void QuequeInit(void)
{
    t_stack1 = StackInit(5);
	t_stack2 = StackInit(5); 
}


void Queque_Push(int dat)
{
	if(Stack_push(t_stack1,dat))
		printf("Queque_Push = %d \r\n",dat);  
	else
		printf("Queque flow \r\n");  
}

int Queque_Pop(void)
{
	int ret = 0;
	if(StackIsEmpty(t_stack2))
	{
		while(!StackIsEmpty(t_stack1))
		{
			Stack_push(t_stack2,Stack_pop(t_stack1));	
		}
	}

	if(StackIsEmpty(t_stack2) && StackIsEmpty(t_stack1))
	{
		printf("Queque empty! \r\n");
		return -1;
	}

	ret = Stack_pop(t_stack2);
	printf("Queque_Pop = %d \r\n",ret); 
	return ret;
}

int main()  
{  
    int ret = 0;  

	QuequeInit();
    Queque_Push(10);  
    Queque_Push(20);  
    Queque_Push(30);  
	Queque_Push(40);
	Queque_Push(50);
    Queque_Push(60);   //printf("Queque flow! \r\n");  
  
    ret = Queque_Pop();    
    ret = Queque_Pop();      
    ret = Queque_Pop();  
	ret = Queque_Pop(); 
	ret = Queque_Pop(); 
    ret = Queque_Pop(); //printf("Queque empty! \r\n");  
  
    return 0;  
}  


/********************************************************************自己实现的简易栈功能******************************/

static _stack* StackInit(int stackSize)  
{  
    _stack* myStack = (_stack*)malloc(sizeof(_stack));  
  
    myStack->stacksize = stackSize;  
    myStack->stack_bottom_ptr = (int*)malloc(sizeof(int)*stackSize);  
    myStack->stack_top_ptr = myStack->stack_bottom_ptr;  
  
    return myStack;  
}  
  
  
static BOOL Stack_push(_stack* myStack,int dat)  
{  
    if( myStack->stack_top_ptr - myStack->stack_bottom_ptr >= myStack->stacksize) //myStack->stack_top_ptr - myStack->stack_bottom_ptr/sizeof(int) 此处为何不除以sizeof(int)? 单步调试是发现不除以就已经为1,2,3...  
    {  
       // printf("stack flow! \r\n");  
        return FALSE;  
    }  
    *myStack->stack_top_ptr = dat;  
    myStack->stack_top_ptr ++;  
 //   printf(" Stack_push = %d! \r\n",dat);  
    return TRUE;  
  
}  
  
  
static int Stack_pop(_stack* myStack)  
{  
    if(myStack->stack_top_ptr == myStack->stack_bottom_ptr)  
    {  
        printf("stack empty! \r\n");  
        return FALSE;  
    }  
    myStack->stack_top_ptr --;  
//    printf(" Stack_pop = %d! \r\n",*myStack->stack_top_ptr);  
    return *myStack->stack_top_ptr;  
  
}  
 

static BOOL StackIsEmpty(_stack* myStack)
{
	return (myStack->stack_top_ptr == myStack->stack_bottom_ptr) ? TRUE:FALSE;
}

你可能感兴趣的:(数据结构)