๐ ๊ณต๋ถํ๋ ์ง์ง์ํ์นด๋ ์ฒ์์ด์ง?
[Coding Interview University] ํ : ์ด๋ก ๋ฐ ๊ตฌํ ๋ณธ๋ฌธ
๐ฉ๐ป ์ปดํจํฐ ๊ตฌ์กฐ/Computer Science
[Coding Interview University] ํ : ์ด๋ก ๋ฐ ๊ตฌํ
์ง์ง์ํ์นด 2023. 7. 3. 15:14728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ ์ฝ๋ฉ์ธํฐ๋ทฐ๋ํ ๋์ Git๊ณผ ์์ ์ ์ฐธ๊ณ ํด์ ๊ณต๋ถํ๋ฉฐ ์์ฑํ์์ต๋๋ค :-)>
๐ซง ํ
: FIFO (First In First Out) ์์
: ํ์ ์ ์ฅ๋๋ ํญ๋ชฉ๋ค์ ํ์ ์ถ๊ฐ๋๋ ์์๋๋ก ์ ๊ฑฐ๋๋ค
- ๋๋น ์ฐ์ ํ์ (bfs)
- ์ฒ๋ฆฌํด์ผ ํ ๋ ธ๋์ ๋ฆฌ์คํธ๋ฅผ ์ ์ฅํ๋ ์ฉ๋๋ก ํ ์ฌ์ฉ
- ๋ ธ๋๋ฅผ ํ๋ ์ฒ๋ฆฌํ ๋๋ง๋ค ํด๋น ๋ ธ๋์ ์ธ์ ํ ๋ ธ๋๋ค์ ํ์ ๋ค์ ์ ์ฅ
- ๋ ธ๋๋ฅผ ์ ๊ทผํ ์์๋๋ก ์ฒ๋ฆฌ ๊ฐ๋ฅ
- ์บ์ ๊ตฌํ
๐ซง ํ ๊ตฌํํ๊ธฐ
๐ tail ํฌ์ธํฐ๊ฐ ์๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํํ๊ธฐ
โก๏ธ enqueue(value) - tail์ด ๊ฐ๋ฆฌํค๋ ๊ณณ์ value๋ฅผ ์ถ๊ฐํ๋ค
int main()
{
int keys[] = { 1, 2, 3, 4, 5 };
Queue q;
// ์์ ํค ์ฝ์
for (int key: keys) {
q.enqueue(key);
}
return 0;
}
โก๏ธ dequeue() - value๋ฅผ ๋ฐํํ๊ณ ๊ฐ์ฅ ์ต๊ทผ์ ์ถ๊ฐ๋ ์์(front)๋ฅผ ์ ๊ฑฐํ๋ค.
int main()
{
int keys[] = { 1, 2, 3, 4, 5 };
Queue q;
// ์์ ํค ์ฝ์
for (int key: keys) {
q.enqueue(key);
}
cout << q.dequeue() << endl; // 1์ ์ถ๋ ฅ
cout << q.dequeue() << endl; // 2๋ฅผ ์ถ๋ ฅ
return 0;
}
โก๏ธ empty()
#include <iostream>
#include <stack>
#include <cstdlib>
using namespace std;
// ๋ ๊ฐ์ Stack์ ์ฌ์ฉํ์ฌ Queue ๊ตฌํ
class Queue
{
stack<int> s1, s2;
public:
// Queue์ ์์ดํ
์ถ๊ฐ
void enqueue(int data)
{
// ์ฒซ ๋ฒ์งธ Stack์ ๋ชจ๋ ์์๋ฅผ ๋ ๋ฒ์งธ Stack์ผ๋ก ์ด๋
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
// ํญ๋ชฉ์ ์ฒซ ๋ฒ์งธ Stack์ ํธ์
s1.push(data);
// ๋ชจ๋ ์์๋ฅผ ๋ ๋ฒ์งธ Stack์์ ์ฒซ ๋ฒ์งธ Stack์ผ๋ก ๋ค์ ์ด๋ํฉ๋๋ค.
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
}
// Queue์์ ์์ดํ
์ ๊ฑฐ
int dequeue()
{
// ์ฒซ ๋ฒ์งธ Stack์ด ๋น์ด ์๋ ๊ฒฝ์ฐ
if (s1.empty())
{
cout << "Underflow!!";
exit(0);
}
// ์ฒซ ๋ฒ์งธ Stack์ ์ต์์ ํญ๋ชฉ์ ๋ฐํํฉ๋๋ค.
int top = s1.top();
s1.pop();
return top;
}
};
๐งก ๊ณ ์ ๊ธธ์ด ๋ฐฐ์ด์ ์ฌ์ฉํ์ฌ ๊ตฌํํ๊ธฐ
- enqueue(value) - ์ฌ์ฉ ๊ฐ๋ฅํ ์ ์ฅ ๊ณต๊ฐ์ ๋์ item์ ์ถ๊ฐํ๋ค.
- dequeue() - value๋ฅผ ๋ฐํํ๊ณ ๊ฐ์ฅ ์ต๊ทผ์ ์ถ๊ฐ๋ ์์๋ฅผ ์ ๊ฑฐํ๋ค.
- empty()
- full()
๐ ๋น์ฉ
- a bad implementation using linked list where you enqueue at head and dequeue at tail would be O(n) because you'd need the next to last element, causing a full traversal each dequeue
- enqueue: O(1) (amortized, linked list and array [probing])
- dequeue: O(1) (linked list and array)
- empty: O(1) (linked list and array)
728x90
๋ฐ์ํ
'๐ฉโ๐ป ์ปดํจํฐ ๊ตฌ์กฐ > Computer Science' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Coding Interview University] ์ด์งํ์ : ์ด๋ก ๋ฐ ๊ตฌํ (0) | 2023.07.07 |
---|---|
[Coding Interview University] ํด์ํ ์ด๋ธ : ์ด๋ก ๋ฐ ๊ตฌํ (0) | 2023.07.05 |
[Coding Interview University] ์คํ : ์ด๋ก ๋ฐ ๊ตฌํ (0) | 2023.07.01 |
[Coding Interview University] ๋งํฌ๋ ๋ฆฌ์คํธ : ์ด๋ก ๋ฐ ๊ตฌํ (0) | 2023.06.29 |
[Coding Interview University] ๋ฐฐ์ด : ์ด๋ก ๋ฐ ๊ตฌํ (0) | 2023.06.28 |
Comments