SHyeonL / Future_Internet_LAB_Algorithm

미래 인터넷 연구실 알고리즘 스터디
0 stars 0 forks source link

9093번 - 단어 뒤집기 #4

Open SHyeonL opened 1 year ago

SHyeonL commented 1 year ago
import sys
input = sys.stdin.readline

n = int(input())
stack = []
for i in range(n):
    x = input()
    for j in range(len(x)):
        if x[j] == ' ' or j == len(x) - 1:
            while stack:
                print(stack.pop(), end='')
            if j == len(x) - 1:
                print('\n', end='')
            else:
                print(' ', end='')
        else:
            stack.append(x[j])
yuneojin commented 1 year ago
T = int(input())

for i in range(T):
    string = input()
    string += " "
    s = []
    for j in string:
        if j!=" ":
            s.append(j)
        else:
            while s:
                print(s.pop(), end='')
            print(' ', end='')
    print('\n', end = '')
rhkrdkdms123 commented 1 year ago
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STACK_SIZE 100

typedef int element;

typedef struct {
    element data[MAX_STACK_SIZE];
    int top;
} StackType;

void init_stack(StackType* s) {
    s->top = -1; //스택이 공백상태면 top은 -1
}

int is_empty(StackType* s) {
    return (s->top == -1);
}

int is_full(StackType* s) {
    return (s->top == (MAX_STACK_SIZE - 1));
}

void push(StackType* s, element item) {
    if (is_full(s)) {
        fprintf(stderr, "스택 포화 에러\n");
        return;
    }
    else s->data[++(s->top)] = item;
}

element pop(StackType* s) {
    if (is_empty(s)) {
        fprintf(stderr, "스택 공백 에러\n");
        exit(1);
    }
    else return s->data[(s->top)--];
}

int main(void) {
    int test;

    StackType s;
    init_stack(&s);

    scanf("%d", &test);

    getchar();

    for (int i = 0; i < test; i++) {
        char sentence[1001] = { '\0' };
        scanf("%[^\n]s", sentence);
        getchar();

        sentence[strlen(sentence)] = ' ';
        sentence[strlen(sentence) + 1] = '\0';

        for (int j = 0; j < strlen(sentence); j++) {
            if (sentence[j] == ' ') {
                while (!is_empty(&s)) printf("%c", pop(&s));
                printf(" ");
            }
            else {
                push(&s, sentence[j]);
            }
        }
        printf("\n");
    }

    return 0;
}