用两个栈实现队列的操作代码

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

typedef struct node
{
	int nValue;
	struct node *pNext;
}MyStack;

typedef struct node2
{
	MyStack *pTop;
	int nCount;
}Stack;

typedef struct node3 
{
	Stack *pStack1;
	Stack *pStack2;
	int nCount;
}Queue;


void s_Init(Stack **pStack)
{
	*pStack = (Stack *)malloc(sizeof(Stack));
	(*pStack)->pTop = NULL;
	(*pStack)->nCount = 0;
}

void s_Push(Stack *pStack,int nNum)
{
	if(pStack == NULL)
	{
		printf("stack is not exist.\n");
		return;
	}

	MyStack *pTemp = NULL;
	pTemp = (MyStack*)malloc(sizeof(MyStack));
	pTemp->nValue = nNum;
	
	//新来节点的下一个是原来的栈顶
	pTemp->pNext = pStack->pTop;

	//新来节点成为新的栈顶
	pStack->pTop = pTemp;
	
	//计数器
	pStack->nCount++;
}

int s_Pop(Stack *pStack)
{
	if(pStack == NULL || pStack->pTop == NULL)return -1;

	MyStack *pDel = NULL;
	pDel = pStack->pTop;

	int nNum;
	nNum = pDel->nValue;

	//原来栈顶的下一个成为新的栈顶
	pStack->pTop = pStack->pTop->pNext;

	free(pDel);
	pDel = NULL;

	pStack->nCount--;
	return nNum;
}

void s_Clear(Stack *pStack)
{
	if(pStack == NULL)return;

	while(pStack->nCount != 0)
	{
		s_Pop(pStack);
	}
}

void s_Destroy(Stack **pStack)
{
	s_Clear(*pStack);
	free(*pStack);
	*pStack = NULL;
}

int s_GetCount(Stack *pStack)
{
	if(pStack == NULL)return -1;
	return pStack->nCount;
}

MyStack *s_GetTop(Stack *pStack)
{
	if(pStack == NULL)
	{
		printf("stack is not exist.\n");
		exit(1);
	}

	return pStack->pTop;
}
int s_IsEmpty(Stack *pStack)
{
	if(pStack == NULL)return -1;

	return pStack->nCount != 0 ? 0:1;
}

//--------------------------------------------------------------------------------------
void q_Init(Queue **pQueue)
{
	*pQueue = (Queue*)malloc(sizeof(Queue));
	(*pQueue)->pStack1 = NULL;
	(*pQueue)->pStack2 = NULL;

	(*pQueue)->nCount = 0;
	s_Init(&((*pQueue)->pStack1));
	s_Init(&((*pQueue)->pStack2));
}

void q_Push(Queue *pQueue,int nNum)
{
	if(pQueue == NULL || pQueue->pStack1 == NULL || pQueue->pStack2 == NULL)return;

	//栈1  入队 栈2 出队
	//栈2 里有元素 将元素依次弹出放入栈1
	while(!s_IsEmpty(pQueue->pStack2))
	{
		s_Push(pQueue->pStack1,s_Pop(pQueue->pStack2));
	}
	//新来元素入栈1
	s_Push(pQueue->pStack1,nNum);
	pQueue->nCount++;
}

int q_Pop(Queue *pQueue)
{
	if(pQueue == NULL || pQueue->pStack1 == NULL || pQueue->pStack2 == NULL || pQueue->nCount == 0)return -1;

	//栈1有元素 依次弹出 压入栈2
	while(!s_IsEmpty(pQueue->pStack1))
	{
		s_Push(pQueue->pStack2,s_Pop(pQueue->pStack1));
	}
	int nNum;
	nNum = s_Pop(pQueue->pStack2);
	pQueue->nCount--;
	return nNum;
}

int main()
{
	Queue *pQueue = NULL;
	q_Init(&pQueue);
	q_Push(pQueue,1);


	printf("%d\n",q_Pop(pQueue));
	printf("%d\n",q_Pop(pQueue));
	q_Push(pQueue,2);
	q_Push(pQueue,3);

	printf("%d\n",q_Pop(pQueue));
	q_Push(pQueue,4);
	printf("%d\n",q_Pop(pQueue));


	return 0;
}

猜你喜欢

转载自blog.csdn.net/aaa_cainiao_66666/article/details/79828375