Home queue11.cpp
Post
Cancel

queue11.cpp

queue11.cpp

Updated at June 15, 2023 10:14AM:

  - Included a check/conditional where there is no second highest element at all!

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// 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;

    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;
        }

        int secondHighestElement(){
            int biggest = 0;
            int biggest2 = 0;
            bool isFound = false;
            for (node* i = head; i != nullptr; i = i -> next){
                if (i -> data > biggest){
                    biggest = i -> data;
                }
            }
            for (node* i = head; i != nullptr; i = i -> next){
                if (i -> data > biggest2 && i -> data < biggest){
                    biggest2 = i -> data;
                    isFound = true;
                }
            }
            if (!isFound){
                return 0;
            }
            return biggest2;
        }
};
int main(){
    Queue q1({3, 5, 2, 4, 10, 1, 20, 40, 31, 28, 50});
    q1.print();
    if (q1.secondHighestElement() == 0){
        cout << "No second highest element" << endl;
    }
    else {
        cout << q1.secondHighestElement() << endl;
    }
    Queue q2({1, 1, 1});
    q2.print();
    if (q2.secondHighestElement() == 0){
        cout << "No second highest element" << endl;
    }
    else {
        cout << q2.secondHighestElement() << endl;
    }
    return 0;
}

Console Output

1
2
3
4
Queue Elements: 3 5 2 4 10 1 20 40 31 28 50 
40
Queue Elements: 1 1 1
No second highest element

Go Back

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