栈与队列

程序员代码面试指南

 

题目描述

用两个栈实现队列,支持队列的基本操作。

输入描述:

第一行输入一个整数N,表示对队列进行的操作总数。

下面N行每行输入一个字符串S,表示操作的种类。

如果S为"add",则后面还有一个整数X表示向队列尾部加入整数X。

如果S为"poll",则表示弹出队列头部操作。

如果S为"peek",则表示询问当前队列中头部元素是多少。

输出描述:

对于每一个为"peek"的操作,输出一行表示当前队列中头部元素是多少。

思路
  • push_back操作:stack1.push(new element),将入队的元素都先存在stack1中
  • pop_front,front操作:stack2用于存储队列的头部信息

   首先判断stack2是否为空,如果stack2为空,先将stack1中的元素出栈,然后按顺序压入stack2中

   如果stack2非空,pop_front = stack2.pop(), front = stack2.top();

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
    int N;
    stack<int> stack1, stack2;
    string tmp;
    cin >> N;
    for(int i = 0; i < N; i++){
        cin >> tmp;
        if(tmp == "add") {
            int num;
            cin >> num;
            stack1.push(num);
        }
        else{
            if(stack2.empty()){
                while(!stack1.empty()){
                    stack2.push(stack1.top());
                    stack1.pop();
                }
            }
            if(!stack2.empty()){
                if(tmp == "peek") 
                    cout << stack2.top() <<endl;
                else if(tmp == "poll")
                    stack2.pop();
            }
        }
    }
    return 0;    
}

 

题目描述

一个栈中元素的类型为整型,现在想将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。如何完成排序?

输入描述:

第一行输入一个N,表示栈中元素的个数
第二行输入N个整数a_iai表示栈顶到栈底的各个元素

输出描述:

输出一行表示排序后的栈中栈顶到栈底的各个元素。
示例1

输入

5
5 8 4 3 6

输出

8 6 5 4 3
先将数据从小到大的存入辅助栈help中
1)用cur保存stack中的栈顶元素
2) 如果辅助栈为空或者cur小于等于help栈顶元素,则直接将cur入栈
3)如果cur大于help栈顶元素,则将help元素取出压入stack中,直到help顶元素小于等于cur,或者help为空,然后将cur压入help中
4)当stack为空时,表示元素都存入help,并且自顶向下为非递减排序,最后将help元素取出压入stack中,排序完成
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     int N;
 5     scanf("%d", &N);
 6     stack<int> stack, help;
 7     for (int i = 0; i < N; i++) {
 8         int tmp;
 9         scanf("%d", &tmp);
10         stack.push(tmp);
11     }
12     //process
13     //s to h
14     while (!stack.empty()) {
15         int cur = stack.top();
16         stack.pop();
17         while (!help.empty() && help.top() < cur) {
18             stack.push(help.top());
19             help.pop();
20         }
21         help.push(cur);
22     }
23     //h to s
24     while (!help.empty()) {
25         stack.push(help.top());
26         help.pop();
27     }
28     //print
29     for (int i = 0; i < N; i++) {
30         if (i != 0) printf(" ");
31         printf("%d", stack.top());
32         stack.pop();
33     }
34     return 0;
35 }
View Code

 

posted @ 2019-08-31 22:31  night9zzzz  阅读(345)  评论(0编辑  收藏  举报