双栈模拟队列

 1 #include <iostream>

 2 #include <stack>

 3 using namespace std;

 4 

 5 class QueuebyStack

 6 {

 7 public:

 8     void enqueue(char ch)

 9     {

10         s1.push(ch);

11     }

12     void dequeue()

13     {

14         if(s2.empty())

15         {

16             while(!s1.empty())

17             {

18                 char temp = s1.top();

19                 s2.push(temp);

20                 s1.pop();

21             }

22         }

23         s2.pop();

24     }

25     bool empty()

26     {

27         return s1.empty()&&s2.empty();

28     }

29     char front()

30     {

31         if(s2.empty())

32         {

33             while(!s1.empty())

34             {

35                 char temp = s1.top();

36                 s2.push(temp);

37                 s1.pop();

38             }

39         }

40         return s2.top();

41     }

42     long size() const

43     {

44         return s1.size()+s2.size();

45     }

46 private:

47     stack<char> s1;

48     stack<char> s2;

49 };

50 

51 int main()

52 {

53     QueuebyStack q;

54     char ch;

55     while(cin>>ch&&ch != '0')

56     {

57         q.enqueue(ch);

58     }

59     while(!q.empty())

60     {

61         cout<<q.front()<<" ";

62         q.dequeue();

63     }

64     cout<<endl;

65     return 0;

66 }
View Code

 

你可能感兴趣的:(队列)