Description
A list is a sequence of zero or more elements, expressed in this form: [a1, a2, a3, ... , an], where each ai is one or more consecutive digits or lowercase letters. i.e. each list begins with a left square bracket, then zero or more elements separated by a single comma, followed by a right square bracket. There will be no whitespace characters (spaces, TABs etc) within a list.
In this problem, we use two list operations: append (++) and remove (--).
1. A ++ B: append elements in B to the end of A.
2. A -- B: remove all the elements in B, from A. If something appears more than once in B, remove it that many times in A. If there are many equal elements in A to choose from, remove them from left to right (until all occurrences are removed, or there is no need to remove more elements).
Your task is to write a calculator, evaluating simple expressions or the form "list1 ++ list2" or "list1 -- list2".
Input
There will be at most 10 expressions, one in each line, each having the form "list1 ++ list2" or "list1 -- list2", with no more than 80 characters in total (not counting the newline character). There will be exactly two spaces in each line: one before and one after the operator. Input ends with a single dot. The input is guaranteed to satisfy the restrictions stated above.
Output
For each expression, print its result on a single line.
Sample Input
[1,2,3] ++ [1,2,3] [a,b,c,t,d,e,t,x,y,t] -- [t] [a,b,c,t,d,e,t,x,y,t] -- [t,t,t,t] [123] ++ [456] .
Sample Output
[1,2,3,1,2,3] [a,b,c,d,e,t,x,y,t] [a,b,c,d,e,x,y] [123,456]
水题,字符串的处理,容易出错!
#include <iostream> #include <stdio.h> #include <string> #include<list> using namespace std; int main() { list<string > q1,q2; list<string>::iterator ptr1,ptr2; char c; string str; int flag,temp,j; while(scanf("%c",&c)!=EOF) { if(c=='.') break; q1.clear(); q2.clear(); while((c=getchar())!=EOF) { if(c==']') break; str=""; str+=c; while((c=getchar())!=',') { if(c==']') break; str+=c; } q1.push_back(str); if(c==']') break; } getchar(); if((c=getchar())=='+') flag=1; else flag=0; getchar(); getchar(); getchar(); while((c=getchar())!=EOF) { if(c==']') break; str=""; str+=c; while((c=getchar())!=',') { if(c==']') break; str+=c; } q2.push_back(str); if(c==']') break; } getchar(); if(flag) { printf("["); temp=0; for(ptr1=q1.begin(),j=1;ptr1!=q1.end();ptr1++,j++) { if(j!=q1.size()) { cout<<*ptr1<<","; temp=1; } else { cout<<*ptr1; temp=1; } } for(ptr1=q2.begin(),j=1;ptr1!=q2.end();ptr1++,j++) { cout<<","<<*ptr1;//这里要特别注意,错了几次 } printf("]\n"); } else { for(ptr1=q2.begin();ptr1!=q2.end();ptr1++) { for(ptr2=q1.begin();ptr2!=q1.end();ptr2++) { if(*ptr1==*ptr2) { *ptr2="A"; break; } } } temp=0; for(ptr2=q1.end(),ptr2--,j=q1.size();j>=0;ptr2--,j--) { if(*ptr2!="A") { temp=j; break; } } cout<<"["; for(ptr1=q1.begin(),j=1;ptr1!=q1.end();ptr1++,j++) { if((*ptr1!="A")&&(j!=temp)) cout<<*ptr1<<","; else if((*ptr1!="A")) cout<<*ptr1; } printf("]\n"); } } return 0; }