In: Computer Science
C++ Given Stack Code, Implements Queue. enqueue, dequeue. Modify to function like Queue. Stack #ifndef STACK_H #define STACK_H #include "Node.h" template class Stack { private: Node* top; public: // Constructor Stack() { top = nullptr; } void push(Object ab) { if (top != nullptr) { Node* newNode = new Node(ab, *top); top = newNode; } else { Node* newNode = new Node(ab); top = newNode; } } Object pop() { if (top != nullptr) { Node *returnVal = top; top = top->getNext(); Object returnObject = returnVal->getItem(); delete returnVal; return returnObject; } else { return Object(); } } bool isThere(Object a) { Node* Copy = top; while (Copy != nullptr) { if (Copy->getItem() == a) { return true; } Copy = Copy->getNext(); } return false; } }; #endif //STACK_H
View comments (1)
Queue #ifndef STACK_H #define STACK_H #include "Node.h" template class Stack { private: Node* top; public: // Constructor Stack() { top = nullptr; } // enqueue() operation will be same as push(), changes sholud be made only in pop() method to implement //dequeue() void push(Object ab) { if (top != nullptr) { Node* newNode = new Node(ab, *top); top = newNode; } else { Node* newNode = new Node(ab); top = newNode; } } Object pop() { Node * previous; // to previous node address Node * front; // to hold the address of front node front=top; //initialize front with top address if (front== nullptr) { // zero node case return Object(); } if(front.getNext() == nullptr) // single node case { top=nullptr; Object returnObject = front.getItem(); delete front; return returnObject; } while(front.getNext()!=nullptr)// more than one node case { previous=front; front=front.getNext(); } previous.Next=nullptr; /*include this line only if know what attribute is defined inside the Node struct/class to hold the link of next node in current node to set the second bottom-most node's next field to point nullptr. so replace the attribute "Next" by actual attribute that is defined in Node struct/class.*/ Object returnObject = front.getItem(); delete front; return returnObject; } bool isThere(Object a) { Node* Copy = top; while (Copy != nullptr) { if (Copy->getItem() == a) { return true; } Copy = Copy->getNext(); } return false; } }; #endif //STACK_H