๐Ÿ“ฆ Chango/๐Ÿงฉ Data Structure

๋ฐฐ์—ด๊ณผ ๋ฆฌ์ŠคํŠธ๋กœ ํ ๊ตฌํ˜„ํ•˜๊ธฐ

์„ ๋‹ฌ 2022. 9. 4. 00:46
๋ฐ˜์‘ํ˜•
ํ์— ๋Œ€ํ•œ ์ •์˜๋Š” ์ด๋ฏธ ์•Œ๊ณ  ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ  "๊ตฌํ˜„"์— ์ดˆ์ ์„ ๋งž์ถฐ ํฌ์ŠคํŒ…ํ•ฉ๋‹ˆ๋‹ค

 

๋ฐฐ์—ด

๋กœ ํ๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ๋Š” front ์™€ rear ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ธ๋ฑ์Šค๋ฅผ ๋‘๊ฐœ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.

๊ตฌํ˜„ ์ž์ฒด๋Š” ์‰ฝ์ง€๋งŒ ํ•œ๋ฒˆ ๋ฐ์ดํ„ฐ๋ฅผ ๊บผ๋‚ด๋ฉด ํ•ด๋‹น ์ธ๋ฑ์Šค๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์–ด์„œ ๋‚ญ๋น„๋  ์ˆ˜ ์žˆ๋‹ค.
-> ์ด์— ๋ณดํ†ต ์›ํ˜•ํ๋ฅผ ์ด์šฉํ•˜์—ฌ ๋‚ญ๋น„๋ฅผ ์ค„์ธ๋‹ค.

  • push : ๋ฐฐ์—ด์— ๊ฐ’์„ ์‚ฝ์ž…ํ•˜๊ณ  rear++
  • pop : ๋ฐฐ์—ด์—์„œ ๊ฐ’์„ ์‚ญ์ œํ•˜๊ณ  rear--

 

  • front ๊ฐ€ rear๋ฅผ ์ถ”์›”ํ–ˆ์„ ๋•Œ -> isEmpty
  • rear๊ฐ€ ๋ฐฐ์—ด ํฌ๊ธฐ์™€ ๊ฐ™์•„์กŒ์„ ๋•Œ -> isFull
#include <iostream>

using namespace std;

const int maxSize = 5;

class QueueByArray {
public:
    bool isEmpty();
    bool isFull();
    
    void push(int v);
    int pop();
    
private:
    int front = 0;
    int rear = 0;
    
    int queue[maxSize];
};

bool QueueByArray:: isEmpty() {
    if(front == rear) return true;
    else return false;
}

bool QueueByArray:: isFull() {
    if( (rear+1) % maxSize == front) return true;
    return false;
}

void QueueByArray:: push(int v) {
    if(isFull()) return;
    
    rear = (rear+1) % maxSize;
    queue[rear] = v;
}

int QueueByArray:: pop() {
    if(isEmpty()) return -1;
    
    int tmp = front;
    front = (front+1) % maxSize;
    return queue[tmp];
}



๋ฆฌ์ŠคํŠธ

๋กœ ํ๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ๋Š” front ์™€ rear์— ํ•ด๋‹นํ•˜๋Š” ๋…ธ๋“œ๋ฅผ ์„ ์–ธํ•œ๋‹ค.

  • push : ๊ฐ’์— ํ•ด๋‹นํ•˜๋Š” ๋…ธ๋“œ ์ƒ์„ฑ ํ›„ rear ๋…ธ๋“œ์˜ next๋ฅผ ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ์„ค์ •
  • Pop : front ๋…ธ๋“œ์˜ ๊ฐ’์„ ๋ฐ˜ํ™˜ ํ›„ ์‚ญ์ œ

 

  • front ๊ฐ€ Null ์ผ๋•Œ -> isEmpty
#include <iostream>

using namespace std;

class QueueByList {
public:
    struct node {
        int data;
        node* next;
    };
    
    bool isEmpty();
    
    void push(int v);
    int pop();
    
private:
    node* front = NULL;
    node* rear = NULL;
    
    int len = 0;
};

bool QueueByList:: isEmpty() {
    if(front == NULL) return true;
    else return false;
}

void QueueByList:: push(int v) {
    node* temp = new node();
    temp -> data = v;
    temp -> next = NULL;
    
    if(isEmpty()) front = rear = temp;
    else {
        rear -> next = temp;
        rear = temp;
    }
    
    len++;
}

int QueueByList:: pop() {
    if(isEmpty()) return -1;
    
    int val = front -> data;
    
    front = front->next;
    
    len--;
    return val;
}
๋ฐ˜์‘ํ˜•