Question

Study the "Queue as linked list simple example" posted in this module. Rewrite the code to...

Study the "Queue as linked list simple example" posted in this module. Rewrite the code to use array instead of linked lists. Please do not change anything besides the data structure. Instead of linked list use an array. The functionality should remain exactly the same.

LListQueue.cpp

///---------------------------------------------------------------

/// File: LListQueue.cpp

/// Purpose: Implementation file for a demonstration of a queue

/// implemented as an array. Data type: Character

/// Programming Language: C++

///---------------------------------------------------------------

#include "LListQueue.h"

///--------------------------------------------

/// Function: LListQueue()

/// Purpose: Class constructor

/// Returns: void

///--------------------------------------------

LListQueue::LListQueue()

{

head = tail = nullptr;

}

///--------------------------------------------

/// Function: Code137_Queue()

/// Purpose: Class destructor

/// Returns: void

///--------------------------------------------

LListQueue::~LListQueue()

{

ClearQueue();

}

///--------------------------------------------

/// Function: ClearQueue()

/// Purpose: Remove all items from the queue

/// Returns: void

///--------------------------------------------

void LListQueue::ClearQueue()

{

QNode *temp;

while(head != nullptr)

{

temp = head;

head = head->next;

delete temp;

}

head = tail = nullptr; // Reset indices to start over

}

///--------------------------------------------

/// Function: Enqueue()

/// Purpose: Enqueue an item into the queue.

/// Returns: true if enqueue was successful

/// or false if the enqueue failed.

///--------------------------------------------

bool LListQueue::Enqueue(char ch)

{

QNode *temp;

/// Check to see if the Queue is full

if(isFull()) return false;

/// Create new node for the queue

temp = new QNode ();

temp->ch = ch;

temp->next = nullptr;

/// Check for inserting first in the queue

if(head == nullptr)

head = tail = temp;

else

{

tail->next = temp; /// Insert into the queue

tail = temp; /// Set tail to new last node

}

return true;

}

///--------------------------------------------

/// Function: Dequeue()

/// Purpose: Dequeue an item from the Queue.

/// Returns: Character being dequeued or '\0'

/// if dequeue failed.

//--------------------------------------------

char LListQueue::Dequeue()

{

char ch;

QNode *temp;

/// Check for empty Queue

if(isEmpty()) return '\0'; /// Return null character if queue is empty

else

{

ch = head->ch; /// Get character to return

temp = head;

head = head->next; /// Advance head pointer

delete temp; /// Free old head

/// Check to see if queue is empty

if(isEmpty())

{

head = tail = nullptr; /// Reset everything to empty queue

}

}

return ch; /// Return popped character

}

///--------------------------------------------

/// Function: isEmpty()

/// Purpose: Return true if the queue is empty

/// Returns: true if empty, otherwise false

///--------------------------------------------

bool LListQueue::isEmpty()

{

return (head == nullptr);

}

///--------------------------------------------

/// Function: isFull()

/// Purpose: Return true if the queue is full

/// Returns: true if full, otherwise false

///--------------------------------------------

bool LListQueue::isFull()

{

return false;

}

LListQueue.h

#ifndef LLISTQUEUE_H_INCLUDED

#define LLISTQUEUE_H_INCLUDED

///---------------------------------------------------------------

/// File: LListQueue.h

/// Purpose: Header file for a demonstration of a queue implemented

/// as a linked structure. Data type: Character

/// Programming Language: C++

///---------------------------------------------------------------

struct QNode

{

char ch;

QNode *next;

};

class LListQueue

{

private:

QNode *head, *tail; /// Pointers to head and tail of the queue

public:

LListQueue(); /// Class constructor

~LListQueue(); /// Class destuctor

void ClearQueue(); /// Remove all items from the queue

bool Enqueue(char ch); /// Enter an item in the queue

char Dequeue(); /// Remove an item from the queue

bool isEmpty(); /// Return true if queue is empty

bool isFull(); /// Return true if queue is full

};

#endif /// LLISTQUEUE_H_INCLUDED

main.cpp

///---------------------------------------------------------------

/// File: QueueMain.c

/// Purpose: Main file with tests for a demonstration of a queue

/// as a linked structure.

/// Programming Language: C++

///---------------------------------------------------------------

#include "LListQueue.h"

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

char testString[27];

int i;

char ch;

LListQueue *Q;

cout << "Simple Queue Demonstration\n";

cout << "(Queue implemented as an Array - Queue data type is character.)\n\n";

cout << "Creating a queue\n";

Q = new LListQueue();

cout << "Queue created...\n";

/// Test enqueuing and dequing item on a queue

cout << "Testing enqueue and dequeue of single item.\n";

Q->Enqueue('A');

cout << "Enqueued: " << Q->Dequeue() << "\n";

cout << "...done\n\n";

/// Test queue by enqueing letters in a string

strcpy(testString, "abcdefghijklmnopqrasuvwxyz");

/// Try to Enqueue all letters in the string

i = 0;

cout << "Testing enqueuing of string: " << testString << "\n";

while(testString[i] != '\0')

{

if(!Q->Enqueue(testString[i]))

{

cout << "Queue is full. Unable to enqueue " << testString[i] << "\n";

}

i++;

}

cout << "\n\nDone testing enqueue.\n\nNow testing dequeue.\n";

/// Dequeue letters and print them

cout << "Dequeued letters are...\n";

while((ch = Q->Dequeue()) != '\0') /// Dequeue returns null terminator

cout << ch; /// when queue is empty

cout << "\nEnd of queue encountered...\n";

cout << "\n\n...done.\n";

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the C++ code for the above problem with the proper description provided within comments itself. Below code, some sample output screenshots are attached.

If you need any other help for this Comment me below. Thanks

C++ code :

/**
* Queue implementation using linked list C style implementation ( no OOP).
*/

#include<cstdio>
#include<cstdlib>
#include<climits>
#include<iostream>

#define CAPACITY 100 // Queue max capacity

using namespace std;
/** Queue structure definition */
int queuearray[CAPACITY];
int rearptr, frontptr;
/** Queue size */
unsigned int size = 0;

int enqueue(int data);
int dequeue();
int getRear();
int getFront();
void display();
int isEmpty();
int isFull();
string prepMenu();

int main() {
int option, data;

int rear, front;

rearptr = -1;
frontptr = -1;
string menu = prepMenu();
cout << menu << endl;
cin >> option;
while (option != 7) {

switch (option) {
case 1:
cout << "\nEnter data to enqueue (-99 to stop): ";
cin >> data;
while (data != -99) {
/// Enqueue function returns 1 on success
/// otherwise 0
if (enqueue(data))
cout << "Element added to queue.";
else
cout << "Queue is full." << endl;
cout << "\nEnter data to enqueue (-99 to stop): ";
cin >> data;
}

break;

case 2:
data = dequeue();

/// on success dequeue returns element removed
/// otherwise returns INT_MIN
if (data == INT_MIN)
cout << "Queue is empty." << endl;
else
cout << "Data => " << data << endl;

break;

case 3:

/// isEmpty() function returns 1 if queue is emtpy
/// otherwise returns 0
if (isEmpty())
cout << "Queue is empty." << endl;
else
cout << "Queue size => " << size << endl;

break;

case 4:
data = getRear();

if (data == INT_MIN)
cout << "Queue is empty." << endl;
else
cout << "Rear => " << data << endl;

break;

case 5:

data = getFront();

if (data == INT_MIN)
cout << "Queue is empty." << endl;
else
cout << "Front => " << data << endl;

break;

case 6:
display();
break;

default:
cout << "Invalid choice, please input number between (0-5).\n";
break;
}

cout << "\n\n";
cout << menu << endl;
cin >> option;
}
}

/**
* Enqueues/Insert an element at the rear of a queue.
* Function returns 1 on success otherwise returns 0.
*/
int enqueue(int data) {
if(rearptr > CAPACITY) {
frontptr=rearptr=-1;
return 0;
}
queuearray[++rearptr]=data;
size++;
cout<<rearptr;
return 1;
}

/**
* Dequeues/Removes an element from front of the queue.
* It returns the element on success otherwise returns
* INT_MIN as error code.
*/
int dequeue() {
if(frontptr==rearptr) {
return INT_MIN;
}
int data = queuearray[++frontptr];
size--;
return data;
}

/**
* Gets, element at rear of the queue. It returns the element
* at rear of the queue on success otherwise return INT_MIN as
* error code.
*/
int getRear() {
// Return INT_MIN if queue is empty otherwise rear.
return (isEmpty()) ?
INT_MIN :
queuearray[rearptr];
}

/**
* Gets, element at front of the queue. It returns the element
* at front of the queue on success otherwise return INT_MIN as
* error code.
*/
int getFront() {
// Return INT_MIN if queue is empty otherwise front.
return (isEmpty()) ?
INT_MIN :
queuearray[frontptr+1];
}

/**
* Checks, if queue is empty or not.
*/
int isEmpty() {
return (frontptr==rearptr);
}

/**
* Checks, if queue is within the maximum queue capacity.
*/
int isFull() {
return (rearptr > CAPACITY);
}
string prepMenu() {

string menu = "";

menu += " \n-------------------------------------------------------------------\n";
menu += "1.Enqueue 2.Dequeue 3.Size 4.Get Rear 5.Get Front 6.Display 7.Exit\n";
menu += "----------------------------------------------------------------------\n";
menu += "Select an option: ";
return menu;
}
void display() {
for (int t = frontptr+1; t != rearptr+1; t++)
cout << queuearray[t] << " ";
cout << endl << endl;
}
Output :

Add a comment
Know the answer?
Add Answer to:
Study the "Queue as linked list simple example" posted in this module. Rewrite the code to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Help me solve this in C++ Rewrite the code to use array instead of linked lists....

    Help me solve this in C++ Rewrite the code to use array instead of linked lists. Please do not change anything besides the data structure. Instead of linked list use an array. The functionality should remain exactly the same. You can prepare a class if you wish but it is not required. /** * Queue implementation using linked list C style implementation ( no OOP). */ #include <cstdio> #include <cstdlib> #include <climits> #include <iostream> #define CAPACITY 100 // Queue max...

  • PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...

    PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...

  • How do I pass values to this function? class DynIntQueue { struct QueueNode { int value;...

    How do I pass values to this function? class DynIntQueue { struct QueueNode { int value; QueueNode *next; QueueNode(int value1, QueueNode *next1 = nullptr) { value = value1; next = next1; } }; // These track the front and rear of the queue QueueNode *front; QueueNode *rear; public: // Constructor and Destructor DynIntQueue(); ~DynIntQueue(); // Member functions void enqueue(int); void dequeue(int &); bool isEmpty() const; void clear(); }; main #include <iostream> #include "DynIntQueue.h" using namespace std; int main() {DynIntQueue list;...

  • I need help fixing my code.   My output should be the following. Hello, world! : false...

    I need help fixing my code.   My output should be the following. Hello, world! : false A dog, a panic in a pagoda : true A dog, a plan, a canal, pagoda : true Aman, a plan, a canal--Panama! : true civic : true If I had a hi-fi : true Do geese see God? : true Madam, I’m Adam. : true Madam, in Eden, I’m Adam. : true Neil, a trap! Sid is part alien! : true Never odd...

  • C++ I need help to create a program that executes a simple queue data type. You...

    C++ I need help to create a program that executes a simple queue data type. You must define the queue data type and use the enqueue(), dequeue(), and displayQueue() functions. (Dont use C++ STL to execute queue logic) You may use a linked list , or just use a regular C array of integers. The input file (testfile.txt) will be the list of operations to carry out on a queue. Example input file: enqueue 6 enqueue 8 dequeue enqueue 4...

  • Design and implement a class Q that uses Q.java as a code base. The queue ADT...

    Design and implement a class Q that uses Q.java as a code base. The queue ADT must use class LinkedList from Oracle's Java class library and its underlying data structure (i.e. every Q object has-a (contains) class LinkedList object. class Q is not allowed to extend class LinkedList. The methods that are to be implemented are documented in Q.java. Method comment blocks are used to document the functionality of the class Q instance methods. The output of your program must...

  • Are based on the following Queue class code segment class QueueFull {/* Empty exception class */};...

    Are based on the following Queue class code segment class QueueFull {/* Empty exception class */}; Class Queue Empty {/* Empty exception class */}; struct Node//Node structure int data;//Holds an integer Node* next;//Pointer to next node in the queue}; Class Queue//Linked node implementation of Queue ADT {Private: Node* front;//Pointer to front node of queue Node* rear;//pointer to last node of queue Public: Queue ()://default constructor initializes queue to be empty -Queue ();//Deallocates all nodes in the queue Void Add (int...

  • can someone please fix this error in the stack file at line 18 ( class Stack2:public...

    can someone please fix this error in the stack file at line 18 ( class Stack2:public Stack { ) this is thew error ----> expected class name before '{' token Queue.h --> #include "Stack.hpp" template <typename ITEM> class Queue { private: ITEM item; Stack <ITEM> * s1= new Stack<ITEM>; Stack <ITEM> * s2= new Stack<ITEM>; public: Queue(){}; bool enqueue (ITEM item); bool dequeue (ITEM &item); bool check = true; ~Queue(); }; //this is the class which contains the functions of...

  • 1. (40’) In myStack.cpp, implement the member functions of the class myStack, which is the class...

    1. (40’) In myStack.cpp, implement the member functions of the class myStack, which is the class for integer stacks. 2. (20’) In stackTest.cpp, complete the implementation of function postfixTest(), which use an integer stack to evaluate post-fix expressions. For simplicity, you can assume the post-fix expression is input character by character (i.e., not an entire string), and each operand is a non-negative, single-digit integer (i.e., 0,1,…,9). However, you are supposed to detect invalid/ illegal post-fix expression input, e.g., “4 5...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT