今天动手写了个两个栈实现一个队列的代码,第一次写博客,希望为时不晚。
思想很简单,就是一个栈S1用于入队,另一个栈S2用于出队。
#include <stdio.h>
#include <stdlib.h>typedef int EleType;
struct _strcutNode;
struct _strcutQueue;typedef struct _strcutNode * Stack;
typedef struct _strcutQueue * Queue;struct _strcutNode
{EleType Key;
struct _strcutNode * Next;
};struct _strcutQueue
{
Stack S1;
Stack S2;
};void Push(Stack S,EleType Key)
{
Stack tmp;
tmp =(Stack) malloc(sizeof(struct _strcutNode));
tmp->Key = Key;
tmp->Next = S->Next ;
S->Next =tmp;
}EleType Pop(Stack S)
{
Stack tmp;EleType re;
if(S != NULL)
{tmp = S->Next ;
re= tmp->Key ;
S->Next = tmp->Next ;
free(tmp);return re;
}
}
void CreatQueue(Queue Q)
{Q->S1 =(Stack) malloc(sizeof(struct _strcutNode ));
Q->S2 =(Stack) malloc(sizeof(struct _strcutNode ));
Q->S1 ->Next = NULL;
Q->S2 ->Next = NULL;
}void EnQueue(Queue Q,EleType Key)
{printf("%d入队\n",Key);
Push(Q->S1,Key);}
void DeQueue(Queue Q)
{
if(Q->S2 ->Next !=NULL)//S2不为空时,直接将S2栈顶元素出队
{
printf("出队:%d\n", Pop(Q->S2 ));}
else if(Q->S1 ->Next !=NULL) //Q->S2 ->Next == NULL ,将S1栈除了栈底所有元素弹出并压入S2中,// 那么S1栈底元素就是要出队的元素
{
while(Q->S1->Next->Next != NULL)
Push(Q->S2 , Pop(Q->S1 ));
printf("出队:%d\n", Pop(Q->S1));
}else //Q->S2 ->Next == NULL ,Q->S1 ->Next ==NULL
{
printf("队列为空");
}
}void
main()
{
Queue Q;
Q =(Queue)malloc(sizeof(struct _strcutQueue ));
CreatQueue(Q);EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
EnQueue(Q,4);
EnQueue(Q,5);
DeQueue(Q);
DeQueue(Q);
DeQueue(Q);
EnQueue(Q,7);
EnQueue(Q,8);EnQueue(Q,9);
EnQueue(Q,10);
EnQueue(Q,11);DeQueue(Q);
DeQueue(Q);
DeQueue(Q);
DeQueue(Q);
DeQueue(Q);
DeQueue(Q);
EnQueue(Q,-1);
DeQueue(Q);
}