Home queue3.cpp
Post
Cancel

queue3.cpp

queue3.cpp

Go Back

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
// Link to Challenge: https://www.w3resource.com/cpp-exercises/queue/index.php

#include <iostream>
#include <vector>

using namespace std;

class Queue{
    private:

        struct node{
            int data;
            node* next;
        };

        node* head = nullptr;

        // bool isLinked = false;

    public:

        Queue(){

        }

        Queue(std::vector<int> arr){
            enqueue(arr);
        }

        void enqueue(std::vector<int> arr){
            node* tmp = nullptr;
            node* current = nullptr;
            for (int i = 0; i < arr.size(); i++){
                if (head == nullptr){
                    head = new node{arr[i], nullptr};
                    current = head;
                }
                else{
                    tmp = new node{arr[i], nullptr};
                    current -> next = tmp;
                    current = current -> next;
                }
            }
        }

        void print(){
            cout << "Queue Elements: ";
            for (node* i = head; i != nullptr; i = i -> next){
                cout << i -> data << " ";
            }
            cout << endl;
        }

        void sort(){
            for (node* i = head; i != nullptr; i = i -> next){
                for (node* j = i -> next; j != nullptr; j = j -> next){
                    if (i -> data > j -> data){
                        int tmp = i -> data;
                        i -> data = j -> data;
                        j -> data = tmp;
                    }
                }
            }
        }
};

int main(){
    cout << "Test Data: " << endl;
    Queue q1({5, 1, 7, 9, 2, 3});
    cout << "Unsorted " << endl;
    q1.print();
    q1.sort();
    cout << "Sorted " << endl;
    q1.print();
    return 0;
}

Console Output

1
2
3
4
5
Test Data:
Unsorted
Queue Elements: 5 1 7 9 2 3
Sorted
Queue Elements: 1 2 3 5 7 9

Go Back

This post is licensed under CC BY 4.0 by the author.