DS实验题 word

题目:

885822-20161111205037530-659554228.png
885822-20161111205059608-1942917936.png

代码:

//
//  main.cpp
//  word
//
//  Created by wasdns on 16/11/11.
//  Copyright © 2016年 wasdns. All rights reserved.
//

#include <iostream>
#include <string>
#include <string.h>
#include <cstdio>
#include <stack>
#include <cstdlib>
using namespace std;

string store[10005];                        //存储输出的字符串

/*
 输出函数PrintStack:
    先将栈中元素存到store数组中,再逆序输出数组中元素。
 */

void PrintStack(stack<string> ins)
{
    int cnt = 1;
    
    while (!ins.empty()) {
        
        store[cnt++] = ins.top();
        
        ins.pop();
    }
    
    for (int i = cnt-1; i > 0; i--) {
        cout << store[i] << " ";
    }
    
    cout << endl;
}

int main()
{
    int i, n;
    
    stack<string> ins, temp;                //字符串栈,ins为题目中的word栈
                                            //temp为被ctrl+z操作弹出的字符串
    cin >> n;
    
    getchar();
    
    for (i = 0; i < n; i++)
    {
        string statement;                   //输入的字符串
        
        cin >> statement;
        
        if (statement == "ctrl+z")          //当字符串为ctrl+z时
        {
            if (!ins.empty()) {             //且ins栈不为空时
                
                temp.push(ins.top());
                ins.pop();                  //从ins栈中弹出一个字符串并压入temp
                
                continue;
            }
        }
        
        else if (statement == "ctrl+y")     //当字符串为ctrl+y时
        {
            if (!temp.empty()) {            //且temp栈不为空的时候
                
                ins.push(temp.top());
                temp.pop();                 //从temp栈中弹出一个字符串并压入ins
            
            }
            
            else continue;
        }
        
        else if (statement[0] == 'i')       //当进行input操作时
        {
            string str;
            
            cin >> str;
            
            ins.push(str);                  //将字符串压入ins栈
            
            while (!temp.empty()) {         //按照题目要求,将temp栈清空
                temp.pop();
            }
        }
        
    }
    
    //输出:
    
    if (ins.empty())
        cout << "No output" << endl;
    else
        PrintStack(ins);
    
    
    return 0;
}

结果:

885822-20161111205220874-1651121864.png

结论:

这道题目,逻辑主线相对较为清晰,但是需要注意对状态的保存(需要再维护一个栈,保存delete操作弹出的字符串)。

之前没有AC的原因也是因为忽略了上面这一点,只对最近一次弹出的字符串进行保存,一旦出现如下情况:

6
input a
input b
ctrl+z
ctrl+z
ctrl+y
ctrl+y

输出为b,但是正确的答案应该是b a

2016/11/11

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值