CCI_Q3.5

本文参考该作者文章当作编程笔记:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

Q:

使用两个栈实现一个队列MyQueue。

思路:

一个入栈(ss[0]),另一个(ss[1])将ss[0]弹出的数据压入,这样就可以先进先出(FIFO)了。

CODE:

 1 #include<stdio.h>
 2 #define N 10    /*栈的长度*/
 3 typedef struct 
 4 {
 5     int s[N];
 6     int top;
 7 }struct_stack;
 8 int ssFull(struct_stack *ss)
 9 {
10     return ss->top==(N-1);
11 }
12 void ssPush(int i,struct_stack *ss)
13 {
14     if(ssFull(ss))
15         return;
16     ss->s[++ss->top]=i;
17 }
18 int ssEmpty(struct_stack *ss)
19 {
20     return ss->top==-1;
21 }
22 int ssPop(struct_stack *ss)
23 {
24     if(ssEmpty(ss))
25         return -1;
26     return ss->s[ss->top--];
27 }
28 /*如果ss[1]栈为空,需要将栈ss[0]数据弹出,压入栈ss[1]中*/
29 int queuePop(struct_stack *ss)    
30 {
31     if(ssEmpty(ss) && ssEmpty(ss+1))
32         return -1;
33     if(ssEmpty(ss+1))
34     {
35         while(!ssEmpty(ss))
36         {
37             ssPush(ssPop(ss),ss+1);
38         }
39     }
40     return ssPop(ss+1);
41 }
42 int main()
43 {
44     struct_stack ss[2];
45     ss[0].top=ss[1].top=-1;
46     int i;
47     for(i=0;i<N;++i)    /*向队列中压入10个数据*/
48     {
49         ssPush(i,&ss[0]);
50     }
51     for(i=0;i<3;++i)    /*队列弹出3个数据*/
52     {
53         printf("%d\t",queuePop(ss));
54     }
55     putchar('\n');
56     for(i=0;i<N;++i)    /*再向队列中压入10个数据*/
57     {
58         ssPush(N+i,&ss[0]);
59     }
60     for(i=0;i<N+3;++i)    /*队列弹出13个数据*/
61     {
62         printf("%d\t",queuePop(ss));
63     }
64     putchar('\n');
65     return 0;
66 }
View Code

 

posted @ 2014-03-17 10:51  哈士奇.银桑  阅读(130)  评论(0编辑  收藏  举报