进栈出栈问题
#include < iostream >
#include < cstring >
#include < cstdio >
#include < cstdlib >
#include < stack >
using namespace std;
char* calculateOperationSequence(int *originalArray, int *resultArray, int length);
inline bool isSpace(char x){
return x == ' ' || x == '\r' || x == '\n' || x == '\r' || x == '\b' || x == '\t';
}
char * rightTrim(char *str){
int len = strlen(str);
while(--len>=0){
if(isSpace(str[len])){
str[len] = '\0';
}else{
break;
}
}
return str;
}
char * getInputLine(char *buffer, int length){
if(fgets(buffer,length, stdin)==NULL){
return NULL;
}
rightTrim(buffer);
if(strlen(buffer)<=0){
return NULL;
}
return buffer;
}
int splitAndConvert(char* strings,int *array){
char*tokenPtr = strtok(strings," ");
int i=0;
while(tokenPtr!=NULL){
array[i] = atoi(tokenPtr);
i++;
tokenPtr=strtok(NULL," ");
}
return i;
}
int main(){
char line[1000] = {0} ;
while(getInputLine(line,1000)){
int originalArray[30] = {0};
int originalArrayLength = splitAndConvert(line,originalArray);
if(originalArrayLength==0){
break;
}
getInputLine(line, 1000);
int resultArray[30] = {0};
int resultArrayLength = splitAndConvert(line,resultArray);
if(resultArrayLength==0){
break;
}
char *operationSequence = calculateOperationSequence(originalArray, resultArray, resultArrayLength);
if (NULL != operationSequence)
{ // 原来系统提供的代码。这里没有NULL判断
cout<< operationSequence <<endl;
free(operationSequence); // 自己加的
}
else
cout<< "None" <<endl; // 自己加的
}
return 0;
}
//your code is here
//下面才是让写代码的地方,其他的系统已经自动给出。
char* calculateOperationSequence(int* originalArray, int* resultArray, int length)
{
if(NULL==originalArray || NULL==resultArray || length <= 0)
return NULL;
stack mystack;
int resultindex=0,origindex=0;
int index=0;
string operations("");
operations.append("push1");
mystack.push(originalArray[origindex++]);
char tmpstr[1000];
while( resultindex < length){
if(mystack.empty() && origindex < length){
operations.append("|push");
sprintf(tmpstr,"%d",(origindex+1));
operations.append(tmpstr);
mystack.push(originalArray[origindex++]);
}
if(mystack.top() == resultArray[resultindex]) {
operations.append("|pop");
for(index=0;index
if(mystack.top()==originalArray[index])
break;
}
sprintf(tmpstr,"%d",(index+1));
operations.append(tmpstr);
mystack.pop();
resultindex++;
}
else { if(origindex < length) {
operations.append("|push");
sprintf(tmpstr,"%d",(origindex+1));
operations.append(tmpstr);
mystack.push(originalArray[origindex++]);
}
else {
//top!=result and all elements in original are in stack now
//mismatch now
break;
}
}
}
char *ptr=NULL;
if(! mystack.empty()) {
ptr=new char[10];
strcpy(ptr,"None");
}
else {
ptr=new char[operations.length()+1];
strcpy(ptr,operations.c_str());
}
return ptr;
}