0

A queue is a data storage device much like a stack. The difference is that in a stack the last data item stored is the first one retrieved, while in a queue the first data item stored is the first one retrieved. That is, a stack uses a last-in-first-out (LIFO) approach, while a queue uses first-in-first-out (FIFO). A queue is like a line of customers in a bank: The first one to join the queue is the first one served.

Rewrite the STAKARAY program from this chapter to incorporate a class called queue called put() to put a data item on the queue, and one called get () to get data from the instead of a class called stack. Besides a constructor, it should have two functions: one gcue. These are equivalent to push () and pop() in the stack class. Both a queue and a stack use an array to hold the data. However, instead of a single int variable called top. as the stack has, you'll need two variables for a queue: one called head to point to the head of the queue, and one called tail to point to the tail. Items are on the queue at the tail (like the last customer getting in line at the bank) and removed from the queue at the head. The tail will follow the head along the array as items are added and removed from the queue. This results in an added complexity: When either the tail or the head gets to the end of the array, it must wrap around to the beginning. Thus you'll need a statement like

if(tail = MAX-1)

tail = -1;

to wrap the tail, and a similar one for the head. The array used in the queue is sometimes called a circular buffer, because the head and tail circle around it, with the data between them

#include <iostream>

using namespace std;

class Stack

private:

enum MAX= 10);

int st[MAX];

int top;

public:

Stack()

(top = 0; }

void push(int var)

//put number on stack

{st++top] = var; } { return st[top--]; }

//take number off stack





int pop()

int main()

Stack $1;

$1.push(11);

$1.push(22); cout << 1: << s1.pop() <<< endl; //22 cout << 2: << s1.pop() << endl; //11

$1.push(33);

s1.push(44);

s1.push(55); s1.push(66);

cout << 3: << s1.pop() << endl; //66

cout << 4: <<< s1.pop() << endl; //55 cout << 5: << s1.pop() << endl; //44

cout << 6: << s1.pop() << endl; //33

return 0;

}

Confused about what logic should I use here

  • 1
    This logic is reasonably well explained above isn't it? You need two variables (instead of top) one for the front of the queue and one for the back. And you need to wrap around so that the queue isn't necessarily full just because you've reached the end of the buffer. I can see that the detail of implementing this might be tricky, but I'm not sure why the logic is not clear. What exactly are you confused about? – john Dec 04 '22 at 07:37

0 Answers0