ITfeng

 

用栈实现队列

#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
 int data;
 struct list*next;
}List;
typedef struct stack
{
 List*top;
}Stack;
Stack*A;
Stack*B;
void init_stack(Stack*s)
{
 s->top=NULL;
}
void push_stack(Stack*s,int data)
{
 List*newnode=(List*)malloc(sizeof(List));
 newnode->data=data;
 newnode->next=s->top;
 s->top=newnode;  
}
int pop_stack(Stack*s)
{ int temp;
 List*p;
 if(s->top==NULL) 
 {
  printf("stack is empty\n");
  return -1; 
 }
 temp=s->top->data;
 p=s->top;
 s->top=s->top->next;
 free(p);
 return temp;
 
}

void init_queue()
{
 A=(Stack*)malloc(sizeof(Stack));
 B=(Stack*)malloc(sizeof(Stack));
 init_stack(A); 
 init_stack(B); 
}
void inqueue(int data)
{
 push_stack(A,data);  
}
int queue_isEmpty()
{
 if(A->top==NULL && B->top==NULL)
 {
  return 1;
 } 
 else
  return 0;
}
int dequeue()
{
 if(B->top==NULL)
 {
  //栈A数据全部出栈 数据全部进栈B 然后一个数据出栈B
  while(A->top!=NULL)
  {
   push_stack(B,pop_stack(A));
  } 
  return pop_stack(B);  
 } 
 else
 {
  //栈B直接出栈一个元素
  return pop_stack(B); 
 } 
}

int main()
{
 init_queue();
 int i=0;
 for(;i<10;i++)
 {
  inqueue(i);
 } 
 while(!queue_isEmpty())
 {
  printf("%d\n",dequeue());
 } 
 
 
}
思路是:首先开辟两个栈,如果进队列,则体现得是进栈A

如果出队列,体现的是:如果栈B空,则A全部出队列,再全部进栈B,然后栈B出栈一个元素;

如果栈B不空,则栈B出栈一个元素

posted on 2012-04-21 22:13  ITfeng  阅读(178)  评论(0编辑  收藏  举报

导航