题目:用两个栈实现一个队列,队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入节点和在队列头部删除节点。
实现原理如下:
1:定义两个栈,stack1和stack2, stack1栈用于插入队列,stack2用于输出队列。
2:当有数据进队列时把数据插入stack1,
3:当执行输出队列数据时要检测stack2中是否有数据,如果有数据就使stack2出栈即可。
4:如果stack2没有数据,要把stack1中的全部数据都出栈依次到stack2中,然后让stack2出栈一个数据即可。
代码如下:
/*************************************************************************
> File Name: 07.c
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: Tue 04 Mar 2014 12:18:36 AM PST
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN 128
typedef struct stack{
char data[LEN];
int top;
}Stack, *STACK;
STACK InitStack() /*初始化栈,分配空间*/
{
STACK stack;
stack=(STACK)malloc(sizeof(Stack));
if(stack==NULL)
{
printf("分配空间失败!\n");
return NULL;
}
stack->top=-1;
return stack;
}
int EmptyStack(STACK stack) /*判断栈空,如果为空返回1*/
{
if(stack->top==-1)
return 1;
else
return 0;
}
int Push(STACK stack,char x) /*进栈操作*/
{
if(stack->top>=(LEN-1))
{
printf("栈已经满了,进栈失败!\n");
return 0;
}
stack->data[stack->top+1]=x;
stack->top++;
return 1;
}
int Pop(STACK stack,char *x) /*出栈操作*/
{
if(EmptyStack(stack))
{
printf("栈空,出栈失败!\n");
return 0;
}
int i;
i=stack->top;
*x=stack->data[i];
stack->top--;
return 1;
}
typedef struct queue{ /*定义队列*/
STACK stack1,stack2;
}Queue,*QUEUE;
int append_Queue(QUEUE queue,char x) /*插入数据x到队列queue*/
{
if(queue->stack1->top==(LEN-1))
{
printf("队列已满!\n");
return 0;
}
printf("%c\n",x);
if(!Push(queue->stack1,x))
{
printf("队列插入数据出错!\n");
return 0;
}
return 1;
}
int delete_Queue(QUEUE queue) /*删除队列头部节点*/
{
char x;
if(queue->stack2->top<0) /*如果stack2为空,则把stack1中的所有数据放到栈2中*/
{
while((queue->stack2->top<(LEN-1))&&(queue->stack1->top>=0))
{
Pop(queue->stack1,&x);
Push(queue->stack2,x);
}
}
if(queue->stack2->top==-1)
{
printf("这是空队列!\n");
exit(1);
}
Pop(queue->stack2,&x); /*栈2出栈数据,并放到x中返回*/
return x;
}
QUEUE create_Queue() /*创建队列,即为初始化队列*/
{
QUEUE queue;
queue=(QUEUE)malloc(sizeof(Queue));
queue->stack1=InitStack();
queue->stack2=InitStack();
if(!queue->stack1)
return NULL;
if(!queue->stack2)
return NULL;
return queue;
}
int main()
{
QUEUE queue;
if((queue=create_Queue())==NULL)
{
printf("创建队列失败!\n");
return 1;
}
append_Queue(queue,'a');
append_Queue(queue,'b');
append_Queue(queue,'c');
printf("queue delete:%c\n",delete_Queue(queue));
append_Queue(queue,'d');
append_Queue(queue,'e');
//printf("queue delete:%c\n",delete_Queue(queue));
printf("queue delete:%c\n",delete_Queue(queue));
printf("queue delete:%c\n",delete_Queue(queue));
printf("queue delete:%c\n",delete_Queue(queue));
printf("queue delete:%c\n",delete_Queue(queue));
return 0;
}
最近工作比较忙,前几天写了也没调试,也没敢网上传。