BNU29373:Key Logger(栈的迭代器使用)

Decode the message from the given key logger. The logger consists:

  • ’-’ representing backspace: the character directly before the cursor position is deleted, if there is any.
  • ’<’ (and ’>’) representing the left (right) arrow: the cursor is moved 1 character to the left (right), if possible.
  • alphanumeric characters, which are part of the password, unless deleted later. Here assumes ‘insert mode’: if the cursor is not at the end of the line, and you type an alphanumeric character, then all characters after the cursor move one position to the right.
 

Input

The first line contains a single integer T, indicating the number of test cases.
Each test case contains a string L, with 1 <= Length(L) <= 1000000.

Output

For each test case, output the case number first, then the decoded message string in a line.

Sample Input

2
<<o<IL>>>veU-
HelloAcmer

Sample Output

Case 1: ILove
Case 2: HelloAcmer
 
题意:<代表光标左移,>代表光标右移,-代表删除前面一个元素,要求输出所有操作之后剩余的字符串
思路:一开始直接模拟,超时了,后来百度了一下,如何在链表中间插入元素,于是就学了一下迭代器的用法,用迭代器来做这道题真的是相当简单了
 
#include <stdio.h>
#include <string.h>
#include <list>
#include <algorithm>
using namespace std;

char s1[1000005];
list<char> L;
list<char>::iterator Lpos;//迭代器
int len1;

int main()
{
    int n,cas = 1,i,j;
    int biao;
    scanf("%d",&n);
    while(n--)
    {
        L.clear();
        scanf("%s",s1);
        biao = 0;
        printf("Case %d: ",cas++);
        if(!strstr(s1,"<") && !strstr(s1,">") && !strstr(s1,"-"))
        {
            printf("%s\n",s1);
            continue;
        }
        len1 = strlen(s1);
        Lpos = L.end();//迭代器指向链表末端
        for(i = 0; i<len1; i++)
        {
            if(s1[i] == '<')
            {
                if(Lpos!=L.begin())//迭代器未到头
                    Lpos--;//左移,迭代器左移
            }
            else if(s1[i] == '>')
            {
                if(Lpos!=L.end())//未到末端
                    Lpos++;//右移
            }
            else if(s1[i] == '-')//删除
            {
                if(Lpos != L.begin())
                    Lpos=L.erase(--Lpos);//迭代器前移并删除迭代器所指的元素
            }
            else
            L.insert(Lpos,s1[i]);//在迭代器所指的位置加入元素
        }
        for(Lpos = L.begin();Lpos!=L.end();Lpos++)//迭代器由链表开头到结尾
        printf("%c",*Lpos);
        printf("\n");
    }

    return 0;
}

你可能感兴趣的:(链表,BNU)