For an assignment I was tasked with creating a queue with linked lists. Our professor has given us the test code to insure the program is working properly and for grading. My serve function returns a character. However in the main()
, the function is called twice within one cout
statement, and it returns the character in incorrect order. The getSize
function is also called, however it does not seem to do anything.
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
the display outputs: m a b b. However the cout shows as: a m 4. This should obviously come out as: m a 2.
If i separate the serve and the getSize functions, it works just fine, i.e. cout << q1.serve() << " "; cout << q1.serve() << " "; cout << q1.getSize() << " ";
Below I have posted the code for the linked queue. I imagine I have made a mistake with my node pointers, however I have drawn pictures and re-written the code to no avail. I also apologize if Ive improperly formatted this as it is my first posting. Thank you.
#include <iostream>
using namespace std;
struct Node {
char data;
Node* next;
};
class Queue {
private:
Node* front, * rear;
int size;
public:
Queue();
void append(char);
char serve();
bool isEmpty();
bool isFull();
int getSize();
void display();
};
Queue::Queue() {
front = rear = nullptr;
size = 0;
}
void Queue::append(char v) {
Node* p = new Node;
p->data = v;
p->next = nullptr;
if (size == 0) {
front = rear = p;
size++;
}
else if (size == 1) {
front->next = p;
rear = p;
size++;
}
else {
rear->next = p;
rear = p;
size++;
}
}
char Queue::serve() {
if (front != nullptr) {
Node* temp = front;
char v = temp->data;
front = front->next;
delete temp;
size--;
return v;
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return false;
}
int Queue::getSize() {
return size;
}
void Queue::display() {
Node* runner = front;
while (runner != nullptr) {
cout << runner->data << " ";
runner = runner->next;
}
cout << endl;
}
int main() {
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << endl << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
q1.display();
cout << endl;
/*cout << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
char a = q1.serve(); char b = q1.serve();
cout << a << " " << b << " " << q1.getSize() << endl;*/
}