思路
q1是专职进出栈的,q2只是个中转站
入栈:直接入队列q1即可
出栈:把q1的除最后一个元素外全部转移到队q2中,然后把刚才剩下q1中的那个元素出队列。之后把q2中的全部元素转移回q1中。
(偷得(*^▽^*))图示:
实现代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct node3
{
int nValue;
struct node3 *pNext;
}MyQueue;
typedef struct node4
{
int nCount;
MyQueue *pHead;
MyQueue *pTail;
}Queue;
typedef struct node
{
Queue *pQueue1;
Queue *pQueue2;
int nCount;
}Stack;
void q_Init(Queue **pQueue)
{
*pQueue = (Queue*)malloc(sizeof(Queue));
(*pQueue)->pHead = NULL;
(*pQueue)->pTail = NULL;
(*pQueue)->nCount = 0;
}
void q_Push(Queue *pQueue,int nNum)
{
if(pQueue == NULL)return;
MyQueue *pTemp = NULL;
pTemp = (MyQueue*)malloc(sizeof(MyQueue));
pTemp->nValue = nNum;
pTemp->pNext = NULL;
if(pQueue->pHead == NULL)
{
pQueue->pHead = pTemp;
}
else
{
pQueue->pTail->pNext = pTemp;
}
pQueue->pTail = pTemp;
pQueue->nCount++;
}
int q_Pop(Queue *pQueue)
{
if(pQueue == NULL || pQueue->nCount == 0)return -1;
MyQueue *pDel = NULL;
int nNum;
pDel = pQueue->pHead;
nNum = pDel->nValue;
pQueue->pHead = pQueue->pHead->pNext;
free(pDel);
pDel = NULL;
pQueue->nCount--;
if(pQueue->nCount == 0)
{
pQueue->pTail = NULL;
}
return nNum;
}
int q_IsEmpty(Queue *pQueue)
{
if(pQueue == NULL)return -1;
return pQueue->nCount ? 0:1;
}
void s_Init(Stack **pStack)
{
*pStack = (Stack*)malloc(sizeof(Stack));
(*pStack)->pQueue1 = NULL;
(*pStack)->pQueue2 = NULL;
(*pStack)->nCount = 0;
q_Init(&((*pStack)->pQueue1));
q_Init(&((*pStack)->pQueue2));
}
void s_Push(Stack *pStack,int nNum)
{
if(pStack == NULL || pStack->pQueue1 == NULL || pStack->pQueue2 == NULL)return;
//将元素放入放入非空对列 都空 放入2
if(!q_IsEmpty(pStack->pQueue1))
{
q_Push(pStack->pQueue1,nNum);
}
else
{
q_Push(pStack->pQueue2,nNum);
}
pStack->nCount++;
}
int s_Pop(Stack *pStack)
{
if(pStack == NULL || pStack->pQueue2 == NULL || pStack->pQueue1 == NULL ||
(pStack->pQueue1->nCount == 0 && pStack->pQueue2->nCount == 0))
return -1;
int nNum;
if(!q_IsEmpty(pStack->pQueue1))
{
//1 非空 将尾元素留下 其余元素入到队列2
while(pStack->pQueue1->nCount > 1)
{
q_Push(pStack->pQueue2,q_Pop(pStack->pQueue1));
}
nNum = q_Pop(pStack->pQueue1);
}
else
{
//2 非空 将尾元素留下 其余元素入到队列1
while(pStack->pQueue2->nCount > 1)
{
q_Push(pStack->pQueue1,q_Pop(pStack->pQueue2));
}
nNum = q_Pop(pStack->pQueue2);
}
pStack->nCount--;
return nNum;
}
int main()
{
Stack *pStack = NULL;
s_Init(&pStack);
s_Push(pStack,1);
s_Push(pStack,2);
s_Push(pStack,3);
s_Push(pStack,4);
s_Push(pStack,5);
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
printf("%d\n",s_Pop(pStack));
return 0;
}