C언어로 쉽게 풀어쓴 자료구조 4단원

히치키치·2021년 6월 18일
0

자료구조 수업 강의록과 구글링 등 다양한 자료를 참고하며 풀었습니다. 개인적인 공부에 참고하시는건 언제나 환영이지만 무단으로 재배포하지는 말아주세요..!!

11번

#include<stdio.h>
/* 아이디어
( 를 만나면 stack에 count를 저장하고, count를 올려준다.
) 를 만나면 stack에 pop을 한다.
) 를 만나면 제일 가까운 ( 와 짝궁이므로 스택의 top과 짝궁이 된다.
*/
#define max_size 100
typedef struct Stacktype {
  int stack[max_size];
  int top;
}Stacktype;

void Stack_init(Stacktype* s) {
  s->top = -1;
}
void Stack_push(Stacktype* s, int item) {
  s->stack[++(s->top)] = item;
  return;
}
bool is_empty(Stacktype* s) {
  return s->top == -1;
}
int Stack_pop(Stacktype* s) {
  return s->stack[(s->top)--];	
}
int main(void) {
  Stacktype s;
  Stack_init(&s);
  char input[max_size] = {};
  printf("수식 : ");
  scanf("%s", input);
  printf("괄호 수 : ");
  int i = 0, count = 1;
  while (input[i] != NULL) {
    if (input[i] == '(') {
      Stack_push(&s, count);
      printf("%d ", count);
      count++;}
  else {
    printf("%d ", Stack_pop(&s));}
  i++;
  }
  return 0;
}

13번

#include<stdio.h>
#define MAX_SIZE 100

typedef struct STACK
{ int data[MAX_SIZE];
  int top;
}stack;

void stack_init(stack* s) {
  s->top = -1;}
  
int is_empty(stack* s) {
  return (s->top == -1);}
  
int is_full(stack* s) {
  return(s->top == MAX_SIZE - 1);}
  
void stack_push(stack* s, char item) {
  s->data[++(s->top)] = item;}

int stack_pop(stack* s) {
	return s->data[(s->top)--];}
    
int main() {
  printf("정수를 입력하시오: ");
  char input[MAX_SIZE];
  scanf("%s", input);
  printf("input: %s", input);
  stack s1, s2;
  stack_init(&s1);
  stack_init(&s2);
  int i = 0;
  while (input[i] != NULL) {
  	if (input[i] != input[i + 1]) {
  		stack_push(&s1, input[i] - '0');}
  	i++;
	}
  while (!is_empty(&s1)) {
  	stack_push(&s2, stack_pop(&s1));}
  printf("출력: ");
  while (!(is_empty(&s2))) {
  	printf("%d", stack_pop(&s2));}
  return 0;
}

14번

int stack_size(stack* s) {
  return (s->top + 1);
}

0개의 댓글