peek
Coddy의 힙 & 우선순위 큐 - 자료구조 시리즈 #7 코스 레슨 — 14개 중 6번째.
챌린지
쉬움MinHeap 클래스에 peek 메서드를 추가하세요.
이 메서드는 입력값을 받지 않으며 다음을 반환합니다:
- 힙이 비어 있지 않은 경우, 힙의 최솟값(인덱스 0에 위치한 루트 노드)을 반환합니다.
- 힙이 비어 있는 경우,
-1을 반환합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "minheap.h"
int main() {
MinHeap h;
MinHeap_init(&h);
char line[1024];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "insert") == 0) { char* arg = strtok(NULL, " \t"); if (arg) MinHeap_insert(&h, atoi(arg)); }
if (strcmp(cmd, "peek") == 0) { printf("%d\n", MinHeap_peek(&h)); }
}
return 0;
}