1. Complete the following linked list implementation of FIFO QUEUE in C++ to add
ID: 3679101 • Letter: 1
Question
1. Complete the following linked list implementation of FIFO QUEUE in C++ to add the following member function:
o void peekAll(): display all the elements in the queue. The elements stay in the queue after this operation.
class QUEUE
{
private:
struct node
{ int item; node* next;
node(int x)
{ item = x; next = 0; }
};
typedef node *link;
link head, tail;
public:
QUEUE(int)
{ head = 0; }
int empty() const
{ return head == 0; }
void put(int x)
{ link t = tail;
tail = new node(x);
if (head == 0)
head = tail;
else t->next = tail;
}
int get()
{ int v = head->item; link t = head->next;
delete head; head = t; return v; }
void peekAll()
{ /* implement this part */
}
};
Write a C++ program that creates a queue of up to 100 integers, and then it does the following on user’s input (your program must check for conditions: e.g. no get when the queue is empty):
P x: puts x into queue
G : outputs the element at the head of the queue, and removes this element from the queue
E : outputs “empty” if queue is empty; otherwise “not empty”
F : displays the entire content of the queue in first-in first-out order; no change in the queue
Example Dialogue (input can be read from a specific file, or can be directed to a file):
E <ENTER>
empty
P 1
P 10
E <ENTER>
not empty
F
1 10
P 19
G
1
G
10
E <ENTER>
not empty
P 5
P 20
F
19 5 20
G
19
G
5
G
20
E <ENTER>
empty
G
nothing to get; queue is empty
F
nothing to peek; queue is empty
P 2
E <ENTER>
not empty
F
2
In this assignment, both correctness and efficiency of your programs are important.
Explanation / Answer
#include<iostream>
using namespace std;
class QUEUE
{
private:
struct node
{ int item; node* next;
node(int x)
{ item = x; next = 0; }
};
typedef node *link;
link head, tail;
public:
QUEUE()
{ head = NULL; }
int empty() const
{ return head == NULL; }
void put(int x)
{ link t = tail;
tail = new node(x);
if (head == NULL)
head = tail;
else t->next = tail;
}
int get()
{ int v = head->item; link t = head->next;
delete head; head = t; return v; }
void peekAll()
{
link t = head;
while(t !=NULL){
cout<<t->item<<endl;
t = t->next;
}
}
};
int main(){
QUEUE q;
q.put(2);
q.put(6);
q.put(5);
q.put(9);
q.put(11);
q.put(3);
q.put(21);
q.put(17);
q.put(1);
q.peekAll();
return 0;
}
/*
Output:
2
6
5
9
11
3
21
17
1
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.