出栈列表 outList 325641
进栈列表 inList 123456
栈 s
进栈列表 inList 123456
栈 s
- 令outList索引i<-0,令c<-outList[i].
- 令inList索引p<-0.
- 如果栈不为空,且栈顶元素top(s)=c,则将栈顶元素出栈,跳到第6步。
- 如果inList[p]<c, 将inList[p]进栈,p<-p+1;重复此步骤,直至inList[p]>=c.
- 如果inList[p]!=c, 跳到第7步。否则,将inList[p]进栈并出栈,p<-p+1.
- 令i<-i+1, 如果i<6, 跳回第1步。
- 如果i=7, 输出“成功”;否则输出“失败”。算法结束。
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack{
char * values;
int length;
int top;
}Stack;
void initStack(Stack * s, int length){
s->values = malloc(sizeof(char) * length);
s->length = length;
s->top = 0;
}
void push(Stack * s, char value){
s->values[s->top++] = value;
}
char pop(Stack * s){
s->top--;
return s->values[s->top];
}
int isFull(Stack * s){
return s->top == s->length;
}
int isEmpty(Stack * s){
return s->top == 0;
}
char top(Stack *s){
return s->values[s->top-1];
}
void traverse(Stack * s){
int i;
for(i=0; i<s->top; i++){
printf("%d: %c\n", i, s->values[i]);
}
}
int main(){
Stack s;
initStack(&s, 6);
char input[] = "123456";
char output[6];
scanf("%s", output);
int i;
int c;
int p = 0;
int flag = 0;
char res[12][12];
int res_p=0;
for(i=0; i<6; i++){
c = output[i];
if(!isEmpty(&s) && top(&s)==c){
pop(&s);
sprintf(res[res_p++], "Pop: %c", c);
continue;
}
while(input[p]<c){
push(&s, input[p]);
sprintf(res[res_p++], "Push: %c", input[p]);
p++;
}
if(input[p] == c){
p++;
sprintf(res[res_p++], "Push: %c", c);
sprintf(res[res_p++], "Pop: %c", c);
continue;
}
break;
}
if(i != 7)
printf("failed\n");
else{
printf("successful\n");
for(i=0; i<12; i++){
printf("%s\n", res[i]);
}
}
return 0;
}