TAOCP-2.2.1 Stacks, queues, and deques-exercise 2.

出栈列表 outList 325641
进栈列表 inList 123456
栈 s

  1.  令outList索引i<-0,令c<-outList[i].
  2.  令inList索引p<-0.
  3.  如果栈不为空,且栈顶元素top(s)=c,则将栈顶元素出栈,跳到第6步。
  4.  如果inList[p]<c, 将inList[p]进栈,p<-p+1;重复此步骤,直至inList[p]>=c.
  5.  如果inList[p]!=c, 跳到第7步。否则,将inList[p]进栈并出栈,p<-p+1.
  6.  令i<-i+1, 如果i<6, 跳回第1步。
  7.  如果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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值