-
Priority_queue 구현
1. 연결리스트
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182#include <stdio.h>#include <stdlib.h>#include <string.h>using namespace std;typedef struct Node {int data;Node *next;} Node;typedef struct Priority_Queue{Node *head;int size;} Priority_Queue;void InitPQ(Priority_Queue*pq) {pq->head = NULL;pq->size = 0;}bool IsEmpty(Priority_Queue *pq) {return pq->head == NULL;}void Push(Priority_Queue *pq, int a) {Node *new_node = (Node*)malloc(sizeof(Node));new_node->data = a;new_node->next = NULL;pq->size++;if (IsEmpty(pq)) {pq->head = new_node;}else {Node *prev = NULL;Node *now = pq->head;while (now){int now_data = now->data;if (a > now_data) {//prev와 now사이에 넣을 수 있음break;}prev = now;now = now->next;}if (prev == NULL) {//PQ에 들어가 있는 값중 제일 큼new_node->next = now;pq->head = new_node;}else if (now == NULL) { //들어가 있는 값 중 제일 작음prev->next = new_node;}else {//중간일경우prev->next = new_node;new_node->next = now;}}}int Pop(Priority_Queue *pq) {if (IsEmpty(pq)) return -999;Node *now = pq->head;int re = now->data;pq->head = now->next;free(now);return re;}int main() {Priority_Queue qu;InitPQ(&qu);Push(&qu, 1);Push(&qu, 2);Push(&qu, 3);printf("%d ", Pop(&qu));printf("%d ", Pop(&qu));printf("%d ", Pop(&qu));return 0;}cs '잡다한 지식' 카테고리의 다른 글
c언어로 stack, queue 구현 (0) 2020.09.08 c++ string 변환 (0) 2020.09.07 c 라이브러리 (0) 2020.09.04 lower_bound & upper_bound 함수 (0) 2020.07.12 bitset 사용법 (0) 2020.05.28