如何用栈实现队列的功能

这是一道很著名的面试题,我在复习数据结构的时候碰到了这道题,下面给出我的解法,希望能对有些人有所帮助。

首先,栈的定义是什么,先进后出。队列呢,先进先出。那如何用栈来实现队列呢。

申请两个栈,一个为s1,一个为s2,以s1为主栈,将数据存储到s1中,每次需要进栈的时候,直接进到s1,每次出栈的时候,将s1中所有的元素弹栈,依次压入s2,然后将s2弹栈一次,剩下的再导入s1。这就是栈实现队列的过程。下面我们来看一下代码

  1#include <apue.h>
  2 
  3 typedef struct stacknode
  4 {
  5     int data;
  6     struct stacknode *next;
  7 }_stacknode;
  8 
  9 typedef struct stackctl
 10 {
 11     _stacknode *top;
 12     int count;
 13 }_stackctl;
 14 
 15 void quene(_stackctl *s1,_stackctl *s2);
 16 int main()
 17 {
 18     _stackctl *s1 = (_stackctl *)malloc(sizeof(_stackctl));
 19     _stackctl *s2 = (_stackctl *)malloc(sizeof(_stackctl));
 20     s1->top = NULL;
 21     s1->count = 0;
 22     s2->top = NULL;
 23     s2->count = 0;
 24     quene(s1,s2);
 25 }
 26 void quene(_stackctl *s1,_stackctl *s2)
 27 {
 28     int a = 0,t = 0,x = 0;
 29     while(1)
 30     {
 31         printf("please input any key:!\n");
 32         printf("1:push\n");
 33         printf("2:pop\n");
 34         printf("3:exit\n");
 35         scanf("%d",&a);
 36         if(a == 1)
 37             push(s1,++t);
 38        else if(a == 2)
 39         {
 40             while(s1->count > 0)
 41             {
 42                 pop(s1,&x);
 43                 push(s2,x);
 44             }
 45             pop(s2,&x);
 46             printf("%d have pop!\n",x);
 47             while(s2->count > 0)
 48             {
 49                 pop(s2,&x);
 50                 push(s1,x);
 51             }
 52         }
 53         else if(a == 3)
 54         {
 55             while(s1->count > 0)
 56             {
 57                 pop(s1,&x);
 58                 push(s2,x);
 59             }
 60             while(s2->count > 0)
 61             {
 62                 pop(s2,&x);
 63                 printf("%d have pop\n",x);
 64             }
 65             break;
 66         }
 67     }
68}
 69 int push(_stackctl *s,int x)
 70 {
 71     _stacknode *p;
 72     if(s == NULL)
 73         return -1;
 74     p = (_stacknode *)malloc(sizeof(_stacknode));
 75     p->data = x;
 76     p->next = s->top;
 77     s->top = p;
 78     s->count++;
 79     return 0;
 80 }
 81 
 82 int pop(_stackctl *s,int *x)
 83 {
 84     _stacknode *p;
 85     if(s == NULL)
 86         return -1;
 87     *x = s->top->data;
 88     p = s->top;
 89     s->top = s->top->next;
 90     free(p);
 91     s->count--;
 92     return 0;
 93 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值