Hackerrank | Queue using Two Stacks

133210·2021년 7월 26일
0

2020 문제풀이

목록 보기
13/14
post-thumbnail

https://www.hackerrank.com/challenges/queue-using-two-stacks/problem

Problem

2개의 스택으로 큐를 만들어
기능 1, 2,3 수행하기
1: x를 큐의 마지막에 저장
2: 큐의 맨 앞 요소를 삭제
3: 큐의 맨 앞 요소를 출력

Code

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100000

int stack1[MAX_SIZE];		//큐를 만들기 위한 두 스택
int stack2[MAX_SIZE];

int top1 = -1;			//두 스택의 top값
int top2 = -1;

int IsEmpty1();			//스택 각각의 Empty 체크
int IsEmpty2();
void push1(int data);		//스택 각각에 push
void push2(int data);
int pop1();				//스택 각각을 pop
int pop2();
void Dequeue();			//큐에서 삭제를 위한 Dequeue
int Print_queue();			//출력을 위한 Print_queue

int main() {
    int q;				//시행 횟수 q
    scanf("%d", &q);	
    int type;			//type – 1, 2, 3 지정

    while (q)
    {
        int num;			//1에서 받아오는 숫자
        scanf("%d", &type);	
        if (type == 1)		//type이 1 = queue에 숫자 삽입
        {
            scanf("%d", &num);	
            push1(num);		//스택 1에 push
        }
        else if (type == 2)	//삭제
        {
            Dequeue();
        }
        else if (type == 3)	//출력
        {
            printf("%d\n", Print_queue());
        }
        q--;
    }

    return 0;
}

int IsEmpty1() {
    if (top1 < 0)
        return true;
    else
        return false;
}

int IsEmpty2() {
    if (top2 < 0)
        return true;
    else
        return false;
}

void push1(int data)
{
    stack1[++top1] = data;
}
void push2(int data)
{
    stack2[++top2] = data;
}
int pop1()
{
    return stack1[top1--];
}
int pop2()
{
    return stack2[top2--];
}

void Dequeue() {			//삭제
    if (IsEmpty2())		//스택 2가 비어있으면
    {
        while (!IsEmpty1())	//스택 1이 빌 때 까지
        {
            push2(pop1());	// 스택 1의 요소를 2에 push
        }
    }
    pop2();				//스택 2의 요소를 pop (delete)
}

int Print_queue() {		//출력
    if (IsEmpty2())		//삭제와 기본적인 틀은 같음
    {
        while (!IsEmpty1())
        {
            push2(pop1());
        }
    }
    return stack2[top2];		//대신 pop으로 요소를 꺼내 오지 않고 						  stack2[top2]로 접근하여 출력해줌
}

Result

0개의 댓글