๋ฐ์ํ
ํ์ ๋ํ ์ ์๋ ์ด๋ฏธ ์๊ณ ์๋ค๊ณ ๊ฐ์ ํ๊ณ "๊ตฌํ"์ ์ด์ ์ ๋ง์ถฐ ํฌ์คํ ํฉ๋๋ค
๋ฐฐ์ด
๋ก ํ๋ฅผ ๊ตฌํํ ๋๋ 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;
}
๋ฐ์ํ
'๐ฆ Chango > ๐งฉ Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LRU ์บ์๊ต์ฒด ์๊ณ ๋ฆฌ์ฆ] ํ๋ก๊ทธ๋๋จธ์ค 17680 : ์บ์ (0) | 2022.08.24 |
---|