mardi 6 février 2018

How to use stack to let the characters inside the bracket be repeated for n times in C

Given that I have a pattern "n (characters)",n is from 0 to 9. I need to print the characters inside the bracket will be repeated for n times.

For example, input : 2(abc)4(nn), output : abcabcnnnnnnnn.

#include <stdio.h>

char* bracket(char *word){
    char* temp;
    temp = malloc(sizeof(char));
    scanf("%c", temp);
    while(scanf("%c", temp) == 1){
        if(*temp == ')')
            break;
        else
            strcat(word, temp);
    }
}

int main()
{
    char *word = malloc(sizeof(char));
    char temp;
    while(scanf("%c", &temp) == 1){
        if(temp >= '0' && temp <= '9'){
            bracket(word);
        }
    }
    for(int i = 0; i < 2; i++)
        printf("%s", word);

    return 0;
}

I know how to solve using recursion, but how can I do in stack? Is there any example to help me understanding? I am new to stack.

Aucun commentaire:

Enregistrer un commentaire