SlideShare a Scribd company logo
1 of 38
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top
of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT
combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined
what
* it means to try and pop from an empty stack. Derived classes
should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to
accomplish the task. You will
need to create a stack of the needed type, then use the methods
of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer
values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the
items off the stack to sum them up
and keep them on a second temporary stack so you can put them
all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT
(this is the same implementation
you used in Assignment 10), add the asked for additional
member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to the next node in
* the linked list.
*/
template <class T>
struct Node
{
T item;
Node<T>* link;
};
/** stack (linked list implementation)
* Implementation of the stack ADT as a dynamic linked list.
This implementation
* uses link nodes and grows (and shrinks) the nodes as items
popped and pushed
* onto stack.
*/
template <class T>
class LStack : public Stack<T>
{
public:
LStack(); // default constructor
~LStack(); // destructor
void clear();
bool isEmpty() const;
void push(const T& newItem);
T top() const;
void pop();
int size() const;
private:
Node<T>* stackTop;
int numItems;
};
/** stack (list) constructor
* Constructor for linked list version of stack.
*/
template <class T>
LStack<T>::LStack()
{
stackTop = NULL;
numItems = 0;
}
/** stack (list) destructor
* Destructor for linked list version of stack.
*/
template <class T>
LStack<T>::~LStack()
{
clear();
}
/** stack (list) clear
*
*/
template <class T>
void LStack<T>::clear()
{
Node<T>* temp;
// iterate through Nodes in stack, freeing them up
// as we visit them
while (stackTop != NULL)
{
temp = stackTop;
stackTop = stackTop->link;
// dellocate this Node memory
delete temp;
}
numItems = 0;
}
/** stack (list) isEmpty
*
*/
template <class T>
bool LStack<T>::isEmpty() const
{
return stackTop == NULL;
}
/** stack (list) push
*
*/
template <class T>
void LStack<T>::push(const T& newItem)
{
// dynamically allocate space for the new Node to hold
// this newItem
Node<T>* newNode = new Node<T>;
// initialize the node
newNode->item = newItem;
newNode->link = stackTop;
// now make this new node the new top of stack
stackTop = newNode;
numItems++;
}
/** stack (list) top
*
*/
template <class T>
T LStack<T>::top() const
{
//assert(stackTop != NULL)
if (stackTop == NULL)
{
throw EmptyStackException("LStack<T>::top()");
}
else
{
return stackTop->item;
}
}
/** stack (list) pop
*
*/
template <class T>
void LStack<T>::pop()
{
//assert(stackTop != NULL)
if (stackTop == NULL)
{
throw EmptyStackException("LStack<T>::pop()");
}
else
{
// keep track of the current top, so we can deallocate
Node<T>* temp;
temp = stackTop;
// pop off the top
stackTop = stackTop->link;
// deallocate the old top now
delete temp;
// update size after removal
numItems--;
}
}
/** Stack (list) size
* Return the current size (number of items) on this stack.
*
* @returns int Returns the current stack size.
*/
template <class T>
int LStack<T>::size() const
{
return numItems;
}
Question 9 (10 points) Saved
In our usual stack abstraction we normally do not want or need
to delete from the middle of the
stack. But lets say we have a special case where we need a
method to search for and remove
items somewhere in the stack. Write the following member
function that takes an item of type T
to search for, and searches from the top of the linked list
structure of our LStack, and removes the
first such item it finds. For this question, if the item is not
found you can simply ignore the
request, or print out an error message. As a hint, you may want
to treat it as a special case if the
searchItem is at the top of the stack, and use the pop() method
in that case, otherwise you need to
search through the list, possibly using a current and previous
pointer, and remove the node if you
find one with the matching item (and don't forget to free up the
nodes memory if you find and
delete it).
Here is the prototype for the member function you are to
implement:
/** stack (list) search for item and remove * Search from the
top of the stack for the indicated item, and remove
* the item from the stack if it is found.
*
* @param searchItem The item to search for and remove if
found
*/
template <class T>
void LStack<T>::removeItemFromStack(const T& searchItem)
{
}
ANSWER FOR QUESTION NUMBER 9: IS IT RIGHT OR
WRONG?
template <class T>
void LStack<T>::removeItemFromStack(const T& searchItem)
{
if (this->stackTop == searchItem)
{
if (stackTop->link == NULL)
{
return;
}
T.pop(T.top());
stackTop->item = stackTop->link->item;
searchItem = stackTop->link;
stackTop->link = stackTop->link->link;
free(searchItem);
return;
}
Node<T>* prev = stackTop;
while (prev->link != NULL && prev->link != searchItem)
{
prev = prev->link;
if (prev->link == NULL)
{
return;
}
prev->link = prev->link->link;
free(searchItem);
return;
}
}
Given the following ADT definition of a queue to use:
/** queue (base class)
* The basic definition of the Queue Abstract Data Type (ADT)
* and queue operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Queue
{
public:
/** clear
* Method to clear out or empty any items on queue,
* put queue back to empty state.
* Postcondition: Queue is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the queue is empty. Needed
* because it is undefined to remove from empty queue. This
* function will not change the state of the queue (const).
*
* @returns bool true if queue is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** enqueue
* Add a new item onto back of queue.
*
* @param newItem The item of template type T to add on back
of
* the current queue.
*/
virtual void enqueue(const T& newItem) = 0;
/** front
* Return the front item from the queue. Note in this ADT,
peeking
* at the front item does not remove the front item. Some ADT
combine
* front() and dequeue() as one operation. It is undefined to try
and
* peek at the front item of an empty queue. Derived classes
should
* throw an exception if this is attempted.
*
* @returns T Returns the front item from queue.
*/
virtual T front() const = 0;
/** dequeue
* Remove the item from the front of the queue. It is undefined
what
* it means to try and dequeue from an empty queue. Derived
classes should
* throw an exception if dequeue() from empty is attempted.
*/
virtual void dequeue() = 0;
/** length
* Return the current length or number of item son the queue.
*
* @returns int The current length of this queue.
*/
virtual int length() const = 0;
};
perform the following tasks by writing code that uses a stack to
accomplish the task. You will
need to create a stack of the needed type, then use the methods
of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 10 (5 points) Saved
Use a Queue to reverse a stack in place. Assume you are given a
stack of string values like
Stack<string> s;
using a Queue, cause all of the items in the stack to be reversed.
For example, if you have the
following contents on the stack s
Top
---
bird
cat
dog
turtle
-----
Bottom
After you run your code, you stack contents should look like
Top
---
turtle
dog
cat
bird
-----
Bottom
Answer For Number 10: IS IT RIGHT OR WRONG?
stack <string > s;
s.push("bird");
s.push("cat");
s.push("dog");
s.push("turtle");
Queue<string> q;
int i;
while(!s.empty()) {
q.push(s.top());
s.pop();
}
while(!q.empty()) {
s.push(q.front());
q.pop();
}
Question 12 (5 points)
Using only the ADT Queue abstraction, search for and
determine the maximum value currently in
a Queue of <int> values. When you are done, the Queue should
be unchanged (e.g. you need to
remove and add items onto the queue to do the search). You
may use a special flag value of -99,
as one way to solve this is by pushing on a flag. However, there
are other was, for example recall
that we have a length() method in our ADT which you can use
to determine the number of items
on the queue, or you could use a second temporary queue, etc.
Answer for Number 12: IS IT RIGHT OR WRONG?
int biggestValue(Stack<int> s)
{
Stack<int> temp = s;
int maxValue = temp.top();
while (!temp.isEmpty())
{
temp.pop;
if(temp.top() > max)
{
max = temp.top();
}
}
while(!temp.isEmpty())
{
s.push(temp.top());
temp.pop();
}
return maxValue;
}
Queue Implementation
Given the following array based implementation of a Queue
ADT (this is the same implementation
you used in Assignment 11), add the asked for additional
member methods to the array based
Queue implementation. Recall that the array based
implementation is treating an array of
dynamically allocated memory as a circular buffer, and thus you
have frontIndex and backIndex
variables that point to the index at the front and the back of the
array of items that represent the
current front and back of the queue.
/** queue (array implementation)
* Implementation of the queue ADT as a fixed array. This
* implementation combines a circular buffer implementation, to
make
* sure that both enqueue() and dequeue() operations are O(1)
constant
* time. However, it also uses dynamic memory allocation, and
* demonstrates doubling the size of the allocated space as
needed to
* grow queue if/when the queue becomes full.
*
* @var allocSize The amount of memory currently allocated for
this queue.
* @var numitems The current length or number of items on the
queue.
* @var front A pointer to the index of the front item on the
queue.
* @var back A pointer to the back or last item on the queu.
* @var items The items on the queue. This is a dynamically
allocated array that
* can grow if needed when queue exceeds current allocation.
*/
template
class AQueue : public Queue
{
private:
int allocSize; // amount of memory allocated
int numitems; // The current length of the queue
int frontIndex; // index of the front item of the queue
int backIndex; // index of the last or rear item of the queue
T* items;
public:
AQueue(int initialAlloc = 100); // constructor
~AQueue(); // destructor
void clear();
bool isEmpty() const;
void enqueue(const T& newItem);
T front() const;
void dequeue();
int length() const;
};
/** queue (array) constructor
* Constructor for queue. Default to enough room for 100 items
* NOTE: the front pointer points directly to the index of the
front item, but
* the backIndex pointer points to the index-1 of the item where
next insertion
* will happen.
* NOTE: we treat the items array as a circular buffer, so all
increments of
* indexes must be modulo current allocSize, to wrap backIndex
around to beginning.
*
* @param initialAlloc Initial space to allocate for queue,
defaults to
* 100.
*/
template
AQueue::AQueue(int initialAlloc)
{
allocSize = initialAlloc;
numitems = 0;
frontIndex = 0;
backIndex = allocSize - 1; // back points to (x-1) % allocSize
index
items = new T[allocSize];
}
/** queue (array) destructor
*/
template
AQueue::~AQueue()
{
// free up currently allocated memory
delete [] items;
}
/** queue (array) clear
* Function to initialize the queue back to an empty state.
* Postcondition: frontIndex = 0; backIndex = allocSize-1;
numitems=0; isEmpty() == true
*/
template
void AQueue::clear()
{
frontIndex = 0;
backIndex = allocSize - 1;
numitems = 0;
}
/** queue (array) isEmpty
* Determine whether queue is currently empty or not.
*
* @returns returns true if the queue is empty, otherwise
* returns false.
*/
template
bool AQueue::isEmpty() const
{
return numitems == 0;
}
/** queue (array) enqueue
* Add newItem to the back of the queue.
* Preconditon: The queue exists
* Postcondition: The queue is changed and newItem is added to
the back
* of the queue.
* @param newItem The new item to add to the frontIndex of
this queue.
*/
template
void AQueue::enqueue(const T& newItem)
{
// if queue is full, grow it
if (isFull())
{
// double the current size
int newAllocSize = 2 * allocSize;
// alloc the new space
T* newItems = new T[newAllocSize];
// and copy the queue to the new storage space
// since we are copying anyway, we shift the items from the old
// frontIndex back to index 0
int oldIndex = frontIndex;
for (int index = 0; index < numitems; index++)
{
newItems[index] = items[oldIndex];
oldIndex = (oldIndex + 1) % allocSize;
}
frontIndex = 0;
backIndex = numitems-1;
// free up the old space, start using the new space
delete [] items;
items = newItems;
allocSize = newAllocSize;
}
// add the item, and increment our top
backIndex = (backIndex + 1) % allocSize;
numitems++;
items[backIndex] = newItem;
}
/** queue (array) front
* Peek at and return the front element of the queue.
* Preconditon: The queue exists and is not empty
* Postcondition: If the queue is empty, we throw QueueEmpty
* exception; otherwise, the front element of the queue is
* returned
* @returns T The item of type T currently on the front of this
* queue.
*/
template
T AQueue::front() const
{
//assert(topIndex != 0);
if (isEmpty())
{
throw EmptyQueueException("AQueue::front()");
}
else
{
return items[frontIndex];
}
}
/** queue (array) dequeue
* Remove the front element from the queue. Some ADT
combine dequeue
* and front. We have two separate operations in this ADT.
* Preconditon: The queue exists and is not empty.
* Postcondition: If the queue is empty, we throw QueueEmpty
* exception; otherwise the front element of the queue is
removed
* from the queue.
*/
template
void AQueue::dequeue()
{
// assert(topIndex != 0);
if (isEmpty())
{
throw EmptyQueueException("Aqueue::dequeue()");
}
else
{
numitems--;
frontIndex = (frontIndex + 1) % allocSize;
}
}
/** queue (array) length
* Getter method to access the current queue length.
*
* @returns length Returns the current queue length.
*/
template
int AQueue::length() const
{
return numitems;
}
Question 13 (10 points)
Using the array based queue implementation, search for and
remove the indicated item (if found)
from the middle of this queue. This is of course not a normal
part of the queue abstraction, but is
needed here for a particular application of our queue. When you
remove the item, make sure you
shift all of the other items in the array to fill in the hole for the
removed item. You method can
simply do nothing or print an error if the item that is requested
to be searched for and removed is
not currently present on the queue. Likewise, you only need to
search for and remove the first
instance of the item requested for removal. Here is the signature
for the member function you
should implement:
/** queue (array) search and remove
* Search for the indicated item and remove it from inside of this
* queue if found
*
* @param searchItem A reference to an item of type T that may
be on
* the current queue and should be removed if found.
*/
template
void AQueue::removeItemFromQueue(const T& searchItem)
{
}
Answer for question Number 13: IS IT RIGHT OR WRONG?
template <class T>
void AQueue<T>::removeItemFromQueue(const T& searchItem)
{
if (T.isEmpty())
{
return;
}
else
{
while (int i = 0; i < T.length(); i++)
{
if (T[i] = searchItem)
{
T[i].clear();
}
}
}
}
Please do it in c++

More Related Content

Similar to Given the following ADT definition of a stack to use stack .docx

StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
 
Implement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfImplement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfSIGMATAX1
 
Presentation topic is stick data structure
Presentation topic is stick data structurePresentation topic is stick data structure
Presentation topic is stick data structureAizazAli21
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queueAmit Vats
 
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdfModifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdfLalkamal2
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfJUSTSTYLISH3B2MOHALI
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureZidny Nafan
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureSriram Raj
 

Similar to Given the following ADT definition of a stack to use stack .docx (20)

StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Implement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdfImplement the ADT stack by using an array stack to contain its entri.pdf
Implement the ADT stack by using an array stack to contain its entri.pdf
 
Presentation topic is stick data structure
Presentation topic is stick data structurePresentation topic is stick data structure
Presentation topic is stick data structure
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Algo>Stacks
Algo>StacksAlgo>Stacks
Algo>Stacks
 
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdfModifications highlighted in bold lettersDropOutStack.javaim.pdf
Modifications highlighted in bold lettersDropOutStack.javaim.pdf
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdf
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Chapter03
Chapter03Chapter03
Chapter03
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 

More from shericehewat

You have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxYou have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxshericehewat
 
You have been asked to help secure the information system and users .docx
You have been asked to help secure the information system and users .docxYou have been asked to help secure the information system and users .docx
You have been asked to help secure the information system and users .docxshericehewat
 
You have been asked to participate in a local radio program to add.docx
You have been asked to participate in a local radio program to add.docxYou have been asked to participate in a local radio program to add.docx
You have been asked to participate in a local radio program to add.docxshericehewat
 
You have been hired asa cons.docx
You have been hired asa cons.docxYou have been hired asa cons.docx
You have been hired asa cons.docxshericehewat
 
You have been appointed as a system analyst in the IT department of .docx
You have been appointed as a system analyst in the IT department of .docxYou have been appointed as a system analyst in the IT department of .docx
You have been appointed as a system analyst in the IT department of .docxshericehewat
 
You choose one and I will upload the materials for u.Choose 1 of.docx
You choose one and I will upload the materials for u.Choose 1 of.docxYou choose one and I will upload the materials for u.Choose 1 of.docx
You choose one and I will upload the materials for u.Choose 1 of.docxshericehewat
 
You are Incident Commander and principal planner for the DRNC even.docx
You are Incident Commander and principal planner for the DRNC even.docxYou are Incident Commander and principal planner for the DRNC even.docx
You are Incident Commander and principal planner for the DRNC even.docxshericehewat
 
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docx
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docxYou DecideCryptographic Tunneling and the OSI ModelWrite a p.docx
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docxshericehewat
 
You are working as a behavioral health specialist in a neurological .docx
You are working as a behavioral health specialist in a neurological .docxYou are working as a behavioral health specialist in a neurological .docx
You are working as a behavioral health specialist in a neurological .docxshericehewat
 
You are to write up a reflection (longer than 2 pages) that discusse.docx
You are to write up a reflection (longer than 2 pages) that discusse.docxYou are to write up a reflection (longer than 2 pages) that discusse.docx
You are to write up a reflection (longer than 2 pages) that discusse.docxshericehewat
 
You can only take this assignment if you have the book Discovering t.docx
You can only take this assignment if you have the book Discovering t.docxYou can only take this assignment if you have the book Discovering t.docx
You can only take this assignment if you have the book Discovering t.docxshericehewat
 
You are to interview a woman 50 and older and write up the interview.docx
You are to interview a woman 50 and older and write up the interview.docxYou are to interview a woman 50 and older and write up the interview.docx
You are to interview a woman 50 and older and write up the interview.docxshericehewat
 
You are to complete TWO essays and answer the following questions.  .docx
You are to complete TWO essays and answer the following questions.  .docxYou are to complete TWO essays and answer the following questions.  .docx
You are to complete TWO essays and answer the following questions.  .docxshericehewat
 
You are the vice president of a human resources department and Susan.docx
You are the vice president of a human resources department and Susan.docxYou are the vice president of a human resources department and Susan.docx
You are the vice president of a human resources department and Susan.docxshericehewat
 
You are the purchasing manager of a company that has relationships w.docx
You are the purchasing manager of a company that has relationships w.docxYou are the purchasing manager of a company that has relationships w.docx
You are the purchasing manager of a company that has relationships w.docxshericehewat
 
You are to briefly describe how the Bible is related to the topics c.docx
You are to briefly describe how the Bible is related to the topics c.docxYou are to briefly describe how the Bible is related to the topics c.docx
You are to briefly describe how the Bible is related to the topics c.docxshericehewat
 
You are the manager of an accounting department and would like to hi.docx
You are the manager of an accounting department and would like to hi.docxYou are the manager of an accounting department and would like to hi.docx
You are the manager of an accounting department and would like to hi.docxshericehewat
 
You are the new chief financial officer (CFO) hired by a company. .docx
You are the new chief financial officer (CFO) hired by a company. .docxYou are the new chief financial officer (CFO) hired by a company. .docx
You are the new chief financial officer (CFO) hired by a company. .docxshericehewat
 
You are the manager of a team of six proposal-writing professionals..docx
You are the manager of a team of six proposal-writing professionals..docxYou are the manager of a team of six proposal-writing professionals..docx
You are the manager of a team of six proposal-writing professionals..docxshericehewat
 
You are the environmental compliance officer at a company that is .docx
You are the environmental compliance officer at a company that is .docxYou are the environmental compliance officer at a company that is .docx
You are the environmental compliance officer at a company that is .docxshericehewat
 

More from shericehewat (20)

You have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docxYou have been asked to explain the differences between certain categ.docx
You have been asked to explain the differences between certain categ.docx
 
You have been asked to help secure the information system and users .docx
You have been asked to help secure the information system and users .docxYou have been asked to help secure the information system and users .docx
You have been asked to help secure the information system and users .docx
 
You have been asked to participate in a local radio program to add.docx
You have been asked to participate in a local radio program to add.docxYou have been asked to participate in a local radio program to add.docx
You have been asked to participate in a local radio program to add.docx
 
You have been hired asa cons.docx
You have been hired asa cons.docxYou have been hired asa cons.docx
You have been hired asa cons.docx
 
You have been appointed as a system analyst in the IT department of .docx
You have been appointed as a system analyst in the IT department of .docxYou have been appointed as a system analyst in the IT department of .docx
You have been appointed as a system analyst in the IT department of .docx
 
You choose one and I will upload the materials for u.Choose 1 of.docx
You choose one and I will upload the materials for u.Choose 1 of.docxYou choose one and I will upload the materials for u.Choose 1 of.docx
You choose one and I will upload the materials for u.Choose 1 of.docx
 
You are Incident Commander and principal planner for the DRNC even.docx
You are Incident Commander and principal planner for the DRNC even.docxYou are Incident Commander and principal planner for the DRNC even.docx
You are Incident Commander and principal planner for the DRNC even.docx
 
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docx
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docxYou DecideCryptographic Tunneling and the OSI ModelWrite a p.docx
You DecideCryptographic Tunneling and the OSI ModelWrite a p.docx
 
You are working as a behavioral health specialist in a neurological .docx
You are working as a behavioral health specialist in a neurological .docxYou are working as a behavioral health specialist in a neurological .docx
You are working as a behavioral health specialist in a neurological .docx
 
You are to write up a reflection (longer than 2 pages) that discusse.docx
You are to write up a reflection (longer than 2 pages) that discusse.docxYou are to write up a reflection (longer than 2 pages) that discusse.docx
You are to write up a reflection (longer than 2 pages) that discusse.docx
 
You can only take this assignment if you have the book Discovering t.docx
You can only take this assignment if you have the book Discovering t.docxYou can only take this assignment if you have the book Discovering t.docx
You can only take this assignment if you have the book Discovering t.docx
 
You are to interview a woman 50 and older and write up the interview.docx
You are to interview a woman 50 and older and write up the interview.docxYou are to interview a woman 50 and older and write up the interview.docx
You are to interview a woman 50 and older and write up the interview.docx
 
You are to complete TWO essays and answer the following questions.  .docx
You are to complete TWO essays and answer the following questions.  .docxYou are to complete TWO essays and answer the following questions.  .docx
You are to complete TWO essays and answer the following questions.  .docx
 
You are the vice president of a human resources department and Susan.docx
You are the vice president of a human resources department and Susan.docxYou are the vice president of a human resources department and Susan.docx
You are the vice president of a human resources department and Susan.docx
 
You are the purchasing manager of a company that has relationships w.docx
You are the purchasing manager of a company that has relationships w.docxYou are the purchasing manager of a company that has relationships w.docx
You are the purchasing manager of a company that has relationships w.docx
 
You are to briefly describe how the Bible is related to the topics c.docx
You are to briefly describe how the Bible is related to the topics c.docxYou are to briefly describe how the Bible is related to the topics c.docx
You are to briefly describe how the Bible is related to the topics c.docx
 
You are the manager of an accounting department and would like to hi.docx
You are the manager of an accounting department and would like to hi.docxYou are the manager of an accounting department and would like to hi.docx
You are the manager of an accounting department and would like to hi.docx
 
You are the new chief financial officer (CFO) hired by a company. .docx
You are the new chief financial officer (CFO) hired by a company. .docxYou are the new chief financial officer (CFO) hired by a company. .docx
You are the new chief financial officer (CFO) hired by a company. .docx
 
You are the manager of a team of six proposal-writing professionals..docx
You are the manager of a team of six proposal-writing professionals..docxYou are the manager of a team of six proposal-writing professionals..docx
You are the manager of a team of six proposal-writing professionals..docx
 
You are the environmental compliance officer at a company that is .docx
You are the environmental compliance officer at a company that is .docxYou are the environmental compliance officer at a company that is .docx
You are the environmental compliance officer at a company that is .docx
 

Recently uploaded

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 

Given the following ADT definition of a stack to use stack .docx

  • 1. Given the following ADT definition of a stack to use: /** stack (base class) * The basic definition of the Stack Abstract Data Type (ADT) * and stack operations. All declared functions here are * virtual, they must be implemented by concrete derived * classes. */ template <class T> class Stack { public: /** clear * Method to clear out or empty any items on stack, * put stack back to empty state. * Postcondition: Stack is empty. */ virtual void clear() = 0;
  • 2. /** isEmpty * Function to determine whether the stack is empty. Needed * because it is undefined to pop from empty stack. This * function will not change the state of the stack (const). * * @returns bool true if stack is empty, false otherwise. */ virtual bool isEmpty() const = 0; /** push * Add a new item onto top of stack. * * @param newItem The item of template type T to push on top of * the current stack. */ virtual void push(const T& newItem) = 0; /** top * Return the top item from the stack. Note in this ADT, peeking * at the top item does not remove the top item. Some ADT
  • 3. combine * top() and pop() as one operation. It is undefined to try and * peek at the top item of an empty stack. Derived classes should * throw an exception if this is attempted. * * @returns T Returns the top item from stack. */ virtual T top() const = 0; /** pop * Remove the item from the top of the stack. It is undefined what * it means to try and pop from an empty stack. Derived classes should * throw an exception if pop() from empty is attempted. */ virtual void pop() = 0; /** size * Accessor method to provide the current size of the stack. *
  • 4. * @returns int The current size (number of items) on the stack. */ virtual int size() const = 0; }; perform the following tasks by writing code that uses a stack to accomplish the task. You will need to create a stack of the needed type, then use the methods of the stack abstraction (push, top, pop, etc.) to solve the given task asked for. Question 7 (5 points) Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be unchanged after you have calculated the sum Hint: take the items off the stack to sum them up and keep them on a second temporary stack so you can put them all back on after you have calculated the sum. ANSWER FOR NUMBER 7:
  • 5. int sumStackOfIntegers(Stack<int> currentStack) { Stack<int> tempStack; int sum = 0; while(!currentStack.isEmpty()) { int temp = currentStack.top(); tempStack.push(temp); currentStack.pop(); sum += temp; } while(!tempStack.isEmpty()) { int temp = tempStack.top(); currentStack.push(temp); tempStack.pop(); } return sum; }
  • 6. Stack Implementation Given the following linked list implementation of a Stack ADT (this is the same implementation you used in Assignment 10), add the asked for additional member methods to the linked list stack implementation. /** Node * A basic node contaning an item and a link to the next node in * the linked list. */ template <class T> struct Node { T item; Node<T>* link; }; /** stack (linked list implementation)
  • 7. * Implementation of the stack ADT as a dynamic linked list. This implementation * uses link nodes and grows (and shrinks) the nodes as items popped and pushed * onto stack. */ template <class T> class LStack : public Stack<T> { public: LStack(); // default constructor ~LStack(); // destructor void clear(); bool isEmpty() const; void push(const T& newItem); T top() const; void pop(); int size() const; private:
  • 8. Node<T>* stackTop; int numItems; }; /** stack (list) constructor * Constructor for linked list version of stack. */ template <class T> LStack<T>::LStack() { stackTop = NULL; numItems = 0; } /** stack (list) destructor * Destructor for linked list version of stack. */ template <class T> LStack<T>::~LStack() {
  • 9. clear(); } /** stack (list) clear * */ template <class T> void LStack<T>::clear() { Node<T>* temp; // iterate through Nodes in stack, freeing them up // as we visit them while (stackTop != NULL) { temp = stackTop; stackTop = stackTop->link; // dellocate this Node memory delete temp; }
  • 10. numItems = 0; } /** stack (list) isEmpty * */ template <class T> bool LStack<T>::isEmpty() const { return stackTop == NULL; } /** stack (list) push * */ template <class T> void LStack<T>::push(const T& newItem) { // dynamically allocate space for the new Node to hold // this newItem
  • 11. Node<T>* newNode = new Node<T>; // initialize the node newNode->item = newItem; newNode->link = stackTop; // now make this new node the new top of stack stackTop = newNode; numItems++; } /** stack (list) top * */ template <class T> T LStack<T>::top() const { //assert(stackTop != NULL) if (stackTop == NULL) { throw EmptyStackException("LStack<T>::top()");
  • 12. } else { return stackTop->item; } } /** stack (list) pop * */ template <class T> void LStack<T>::pop() { //assert(stackTop != NULL) if (stackTop == NULL) { throw EmptyStackException("LStack<T>::pop()"); } else
  • 13. { // keep track of the current top, so we can deallocate Node<T>* temp; temp = stackTop; // pop off the top stackTop = stackTop->link; // deallocate the old top now delete temp; // update size after removal numItems--; } } /** Stack (list) size * Return the current size (number of items) on this stack. * * @returns int Returns the current stack size. */ template <class T>
  • 14. int LStack<T>::size() const { return numItems; } Question 9 (10 points) Saved In our usual stack abstraction we normally do not want or need to delete from the middle of the stack. But lets say we have a special case where we need a method to search for and remove items somewhere in the stack. Write the following member function that takes an item of type T to search for, and searches from the top of the linked list structure of our LStack, and removes the first such item it finds. For this question, if the item is not found you can simply ignore the request, or print out an error message. As a hint, you may want to treat it as a special case if the searchItem is at the top of the stack, and use the pop() method in that case, otherwise you need to search through the list, possibly using a current and previous pointer, and remove the node if you
  • 15. find one with the matching item (and don't forget to free up the nodes memory if you find and delete it). Here is the prototype for the member function you are to implement: /** stack (list) search for item and remove * Search from the top of the stack for the indicated item, and remove * the item from the stack if it is found. * * @param searchItem The item to search for and remove if found */ template <class T> void LStack<T>::removeItemFromStack(const T& searchItem) { } ANSWER FOR QUESTION NUMBER 9: IS IT RIGHT OR WRONG?
  • 16. template <class T> void LStack<T>::removeItemFromStack(const T& searchItem) { if (this->stackTop == searchItem) { if (stackTop->link == NULL) { return; } T.pop(T.top()); stackTop->item = stackTop->link->item; searchItem = stackTop->link; stackTop->link = stackTop->link->link; free(searchItem); return; } Node<T>* prev = stackTop; while (prev->link != NULL && prev->link != searchItem)
  • 17. { prev = prev->link; if (prev->link == NULL) { return; } prev->link = prev->link->link; free(searchItem); return; } } Given the following ADT definition of a queue to use: /** queue (base class) * The basic definition of the Queue Abstract Data Type (ADT) * and queue operations. All declared functions here are * virtual, they must be implemented by concrete derived
  • 18. * classes. */ template <class T> class Queue { public: /** clear * Method to clear out or empty any items on queue, * put queue back to empty state. * Postcondition: Queue is empty. */ virtual void clear() = 0; /** isEmpty * Function to determine whether the queue is empty. Needed * because it is undefined to remove from empty queue. This * function will not change the state of the queue (const). * * @returns bool true if queue is empty, false otherwise.
  • 19. */ virtual bool isEmpty() const = 0; /** enqueue * Add a new item onto back of queue. * * @param newItem The item of template type T to add on back of * the current queue. */ virtual void enqueue(const T& newItem) = 0; /** front * Return the front item from the queue. Note in this ADT, peeking * at the front item does not remove the front item. Some ADT combine * front() and dequeue() as one operation. It is undefined to try and * peek at the front item of an empty queue. Derived classes should * throw an exception if this is attempted. *
  • 20. * @returns T Returns the front item from queue. */ virtual T front() const = 0; /** dequeue * Remove the item from the front of the queue. It is undefined what * it means to try and dequeue from an empty queue. Derived classes should * throw an exception if dequeue() from empty is attempted. */ virtual void dequeue() = 0; /** length * Return the current length or number of item son the queue. * * @returns int The current length of this queue. */ virtual int length() const = 0; }; perform the following tasks by writing code that uses a stack to
  • 21. accomplish the task. You will need to create a stack of the needed type, then use the methods of the stack abstraction (push, top, pop, etc.) to solve the given task asked for. Question 10 (5 points) Saved Use a Queue to reverse a stack in place. Assume you are given a stack of string values like Stack<string> s; using a Queue, cause all of the items in the stack to be reversed. For example, if you have the following contents on the stack s Top --- bird cat dog turtle ----- Bottom
  • 22. After you run your code, you stack contents should look like Top --- turtle dog cat bird ----- Bottom Answer For Number 10: IS IT RIGHT OR WRONG? stack <string > s; s.push("bird"); s.push("cat"); s.push("dog"); s.push("turtle"); Queue<string> q; int i;
  • 23. while(!s.empty()) { q.push(s.top()); s.pop(); } while(!q.empty()) { s.push(q.front()); q.pop(); } Question 12 (5 points) Using only the ADT Queue abstraction, search for and determine the maximum value currently in a Queue of <int> values. When you are done, the Queue should be unchanged (e.g. you need to remove and add items onto the queue to do the search). You may use a special flag value of -99, as one way to solve this is by pushing on a flag. However, there are other was, for example recall
  • 24. that we have a length() method in our ADT which you can use to determine the number of items on the queue, or you could use a second temporary queue, etc. Answer for Number 12: IS IT RIGHT OR WRONG? int biggestValue(Stack<int> s) { Stack<int> temp = s; int maxValue = temp.top(); while (!temp.isEmpty()) { temp.pop; if(temp.top() > max) { max = temp.top(); } }
  • 25. while(!temp.isEmpty()) { s.push(temp.top()); temp.pop(); } return maxValue; } Queue Implementation Given the following array based implementation of a Queue ADT (this is the same implementation you used in Assignment 11), add the asked for additional member methods to the array based Queue implementation. Recall that the array based implementation is treating an array of dynamically allocated memory as a circular buffer, and thus you have frontIndex and backIndex variables that point to the index at the front and the back of the array of items that represent the current front and back of the queue. /** queue (array implementation)
  • 26. * Implementation of the queue ADT as a fixed array. This * implementation combines a circular buffer implementation, to make * sure that both enqueue() and dequeue() operations are O(1) constant * time. However, it also uses dynamic memory allocation, and * demonstrates doubling the size of the allocated space as needed to * grow queue if/when the queue becomes full. * * @var allocSize The amount of memory currently allocated for this queue. * @var numitems The current length or number of items on the queue. * @var front A pointer to the index of the front item on the queue. * @var back A pointer to the back or last item on the queu. * @var items The items on the queue. This is a dynamically allocated array that * can grow if needed when queue exceeds current allocation. */
  • 27. template class AQueue : public Queue { private: int allocSize; // amount of memory allocated int numitems; // The current length of the queue int frontIndex; // index of the front item of the queue int backIndex; // index of the last or rear item of the queue T* items; public: AQueue(int initialAlloc = 100); // constructor ~AQueue(); // destructor void clear(); bool isEmpty() const; void enqueue(const T& newItem); T front() const; void dequeue(); int length() const;
  • 28. }; /** queue (array) constructor * Constructor for queue. Default to enough room for 100 items * NOTE: the front pointer points directly to the index of the front item, but * the backIndex pointer points to the index-1 of the item where next insertion * will happen. * NOTE: we treat the items array as a circular buffer, so all increments of * indexes must be modulo current allocSize, to wrap backIndex around to beginning. * * @param initialAlloc Initial space to allocate for queue, defaults to * 100. */ template AQueue::AQueue(int initialAlloc) { allocSize = initialAlloc;
  • 29. numitems = 0; frontIndex = 0; backIndex = allocSize - 1; // back points to (x-1) % allocSize index items = new T[allocSize]; } /** queue (array) destructor */ template AQueue::~AQueue() { // free up currently allocated memory delete [] items; } /** queue (array) clear * Function to initialize the queue back to an empty state. * Postcondition: frontIndex = 0; backIndex = allocSize-1; numitems=0; isEmpty() == true */
  • 30. template void AQueue::clear() { frontIndex = 0; backIndex = allocSize - 1; numitems = 0; } /** queue (array) isEmpty * Determine whether queue is currently empty or not. * * @returns returns true if the queue is empty, otherwise * returns false. */ template bool AQueue::isEmpty() const { return numitems == 0; }
  • 31. /** queue (array) enqueue * Add newItem to the back of the queue. * Preconditon: The queue exists * Postcondition: The queue is changed and newItem is added to the back * of the queue. * @param newItem The new item to add to the frontIndex of this queue. */ template void AQueue::enqueue(const T& newItem) { // if queue is full, grow it if (isFull()) { // double the current size int newAllocSize = 2 * allocSize; // alloc the new space T* newItems = new T[newAllocSize];
  • 32. // and copy the queue to the new storage space // since we are copying anyway, we shift the items from the old // frontIndex back to index 0 int oldIndex = frontIndex; for (int index = 0; index < numitems; index++) { newItems[index] = items[oldIndex]; oldIndex = (oldIndex + 1) % allocSize; } frontIndex = 0; backIndex = numitems-1; // free up the old space, start using the new space delete [] items; items = newItems; allocSize = newAllocSize; } // add the item, and increment our top backIndex = (backIndex + 1) % allocSize;
  • 33. numitems++; items[backIndex] = newItem; } /** queue (array) front * Peek at and return the front element of the queue. * Preconditon: The queue exists and is not empty * Postcondition: If the queue is empty, we throw QueueEmpty * exception; otherwise, the front element of the queue is * returned * @returns T The item of type T currently on the front of this * queue. */ template T AQueue::front() const { //assert(topIndex != 0); if (isEmpty()) {
  • 34. throw EmptyQueueException("AQueue::front()"); } else { return items[frontIndex]; } } /** queue (array) dequeue * Remove the front element from the queue. Some ADT combine dequeue * and front. We have two separate operations in this ADT. * Preconditon: The queue exists and is not empty. * Postcondition: If the queue is empty, we throw QueueEmpty * exception; otherwise the front element of the queue is removed * from the queue. */ template void AQueue::dequeue()
  • 35. { // assert(topIndex != 0); if (isEmpty()) { throw EmptyQueueException("Aqueue::dequeue()"); } else { numitems--; frontIndex = (frontIndex + 1) % allocSize; } } /** queue (array) length * Getter method to access the current queue length. * * @returns length Returns the current queue length. */ template
  • 36. int AQueue::length() const { return numitems; } Question 13 (10 points) Using the array based queue implementation, search for and remove the indicated item (if found) from the middle of this queue. This is of course not a normal part of the queue abstraction, but is needed here for a particular application of our queue. When you remove the item, make sure you shift all of the other items in the array to fill in the hole for the removed item. You method can simply do nothing or print an error if the item that is requested to be searched for and removed is not currently present on the queue. Likewise, you only need to search for and remove the first instance of the item requested for removal. Here is the signature for the member function you should implement:
  • 37. /** queue (array) search and remove * Search for the indicated item and remove it from inside of this * queue if found * * @param searchItem A reference to an item of type T that may be on * the current queue and should be removed if found. */ template void AQueue::removeItemFromQueue(const T& searchItem) { } Answer for question Number 13: IS IT RIGHT OR WRONG? template <class T> void AQueue<T>::removeItemFromQueue(const T& searchItem) { if (T.isEmpty()) {
  • 38. return; } else { while (int i = 0; i < T.length(); i++) { if (T[i] = searchItem) { T[i].clear(); } } } } Please do it in c++