자료구조/Queue

2. 간단한 큐 구현하기 (C++)

갓우태 2018. 9. 26. 18:33

C++로 간단하게 큐를 구현해봤습니다.




Node 클래스


-Set_link : next노드를 연결


-Get_data : 노드의 데이터 반환


-Get_next : 노드의 다음 링크 반환




Queue 클래스


-push : tail에 노드 추가 후, tail을 현재 추가한 노드로


-pop : head 노드 반환 후, head를 다음 노드로


-front : head 반환


-size : 현재 용량 반환


-empty : 비어있으면 true 반환




다음엔 STL queue의 사용법을 알아보겠습니다. 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
using namespace std;
class Node {
private:
    int data;
    Node* next;
public:
    Node();
    Node(int data) : data(data) {}
    void Set_link(Node* node) {
        next = node;
    }
    int Get_data() {
        return data;
    }
    Node* Get_next() {
        return next;
    }
};
class Queue {
private:
    Node* head;
    Node* tail;
    size_t used;
    size_t capacity;
public:
    Queue() {
        head = nullptr;
        tail = nullptr;
    }
    void push(Node* node) {
        if(head == nullptr) {
            head = node;
            tail = node;
        }
        else {
            tail->Set_link(node);
            tail = node;
        }
        used++;
    }
    void pop() {
        if(used == 0) {
            cout << "Queue underflow" << endl;
            return;
        }
        Node* node = head;
        head = head->Get_next();
        used--;
        delete[] node;
    }
    Node* front() {
        return head;
    }
    bool empty() {
        if(used == 0)
            return true;
        return false;
    }
    size_t size() {
        return used;
    }
};
int main() {
    Queue q;
    Node* first = new Node(1);
    q.push(first);
    Node* second = new Node(2);
    q.push(second);
    Node* third = new Node(3);
    q.push(third);
    
    while(!q.empty()) {
        cout << "size : " << q.size() << endl;
        Node* node = q.front();
        q.pop();
        cout << node->Get_data() << endl;
    }
    return 0;
}
cs


반응형