baekjoon 10828

p3pwp3p·2022년 11월 27일
0

baekjoon

목록 보기
38/38

Code

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
	int data;
	struct Node* next;
}Node;

typedef struct Stack {
	struct Node* top;
	int count;
}Stack;

void initStack(Stack* stack) {
	stack->top = NULL;
	stack->count = 0;
}

// if stack is empty, return 1 else 0
int isEmpty(Stack* stack) {
	return stack->count == 0;
}

// push the integer in the stack
void push(Stack* stack, int data) {
	Node* newNode = (Node*)malloc(sizeof(Node));
	newNode->data = data;

	if (isEmpty(stack)) {
		stack->top = newNode;
		newNode->next = NULL;
	}
	else {
		newNode->next = stack->top;
		stack->top = newNode;
	}
	stack->count++;
}

// pop the top node and then display if stack's top is empty, display -1
int pop(Stack* stack) {
	Node* newNode = (Node*)malloc(sizeof(Node));
	
	if (isEmpty(stack)) {
		return -1;
	}
	
	newNode = stack->top;
	stack->top = stack->top->next;	
	stack->count--;
	
	return newNode->data;
}

// display stack's top node, -1
int peek(Stack* stack) {
	Node* newNode = (Node*)malloc(sizeof(Node));

	if (isEmpty(stack)) {
		return -1;
	}
		
	newNode = stack->top;
	
	return newNode->data;
}

// return stack size
int size(Stack* stack) {
	return stack->count;
}

int main(void) {
	Stack stack;
	int num, data;
	char comm[10];

	initStack(&stack);
	scanf("%d", &num);

	for (int i = 0; i < num; i++) {
		scanf("%s", comm);

		if (strcmp(comm, "push") == 0) {
			scanf("%d\n", &data);
			push(&stack, data);
		}
		else if (strcmp(comm, "top") == 0) {
			printf("%d\n", peek(&stack));
		}
		else if (strcmp(comm, "size") == 0) {
			printf("%d\n", size(&stack));
		}
		else if (strcmp(comm, "empty") == 0) {
			printf("%d\n", isEmpty(&stack));
		}
		else if (strcmp(comm, "pop") == 0) {
			printf("%d\n", pop(&stack));
		}
	} 
	

	return 0;
}
profile
💭(。•̀ᴗ-)✧

0개의 댓글