Anzeige

Anzeige

Anzeige

Anzeige

Anzeige

Anzeige

Anzeige

Anzeige

Nächste SlideShare

@author Derek Harter @cwid 123 45 678 @class .docx

Wird geladen in ... 3

14. Oct 2022•0 gefällt mir## 0 gefällt mir

•2 Aufrufe## Aufrufe

Sei der Erste, dem dies gefällt

Mehr anzeigen

Aufrufe insgesamt

0

Auf Slideshare

0

Aus Einbettungen

0

Anzahl der Einbettungen

0

Downloaden Sie, um offline zu lesen

Melden

Bildung

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 t ...

shericehewatFolgen

Anzeige

Anzeige

Anzeige

@author Derek Harter @cwid 123 45 678 @class .docxadkinspaige22

Stack and Queue Apurbo Datta

Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl

NEED THE JAVA CODE FOR TEST METHODS OF THE FOLLOWING CODE- PLEASE HELP.docxLucasmHKChapmant

104332 sri vidhya eng notesKrishnakumar Btech

(674335607) cs2309 java-lab-manualChandrapriya Jayabal

- 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++

Anzeige