I'm working on a variation of the "Car Queue" or "Car Wash" problem in which I have to input how long a car will take to wash, the odds of a car entering the queue for the wash at any given moment, and then receive as output how many cars were washed, how many cars were left in the queue at the end of the day, and how much total waiting time there was. I'm still very new to c++, and have only been using it extensively for the last few months. Its very possible there's an error with my queue implementation code that I didn't catch, but I believe the error is in the main. Currently, I added outputs for every loop, so I could watch the code run, and follow it. It appeared to be accepting a car, and then immediately finishing the wash on it. Then, when no car is present, it simply alternates between a washing and waiting loop. Any help would be greatly appreciated.
#include <assert>
#include <iostream>
#include <fstream>
#include <ostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class Node
{
private:
int item;
Node * next;
public:
Node ();
Node (const int& anItem);
Node (const int& anItem, Node * nextNodePtr);
void setItem (const int& anItem);
void setNext (Node * nextNodePtr);
int getItem ();
Node* getNext();
};
class LinkedQueue
{
private:
Node* backPtr;
Node* frontPtr;
public:
bool isEmpty();
bool enqueue(int& newEntry);
bool dequeue();
int peekFront() const;
LinkedQueue();
~LinkedQueue();
LinkedQueue(const LinkedQueue& aQueue);
};
int main ()
{
srand(1);
int timeForWash;
int minute;
int timeEnteredQueue;
int carsWashed;
int totalQueueMin;
int timeLeftOnCar;
int probOfArrival;
int carsInQueue = 0;
LinkedQueue carQueue;
cout << "Enter time to wash one car:" << endl;
cin >> timeForWash;
cout << endl;
cout << "Enter probability of arrival per minute" << endl;
cin >> probOfArrival;
carsWashed = 0;
totalQueueMin = 0;
timeLeftOnCar = 0;
for (minute = 1; minute <= 20; ++minute)
{
if (rand()%100 <= probOfArrival)
{
carQueue.enqueue(minute);
carsInQueue++;
cout << "Queued" << endl;
}
if ((timeLeftOnCar == 0) && ( !carQueue.isEmpty()))
{
timeEnteredQueue = carQueue.peekFront();
carQueue.dequeue();
totalQueueMin = totalQueueMin + (minute - timeEnteredQueue);
++carsWashed;
carsInQueue--;
timeLeftOnCar = timeForWash;
cout << "Finish" << endl;
}
if (timeLeftOnCar =! 0)
{
timeLeftOnCar -= 1;
cout << "Washing" << endl;
}
if ((timeLeftOnCar == 0) && ( carQueue.isEmpty()))
{
cout << "Waiting" << endl;
}
}
cout << carsWashed << endl;
cout << totalQueueMin << endl;
cout << carsInQueue << endl;
system("pause");
return(0);
};
//Implementation
Node:: Node() : next (nullptr)
{
} // default
Node:: Node (const int& anItem) : item(anItem), next(nullptr)
{
}
Node:: Node (const int& anItem, Node * nextNodePtr) : item(anItem), next(nextNodePtr)
{
}
void Node:: setItem (const int& anItem)
{
item = anItem;
}
void Node:: setNext (Node * nextNodePtr)
{
next = nextNodePtr;
}
int Node:: getItem ()
{
return item;
}
Node * Node:: getNext ()
{
return next;
}
bool LinkedQueue::enqueue(int& newEntry)
{
Node* newNodePtr = new Node(newEntry);
//Insert the new node
if (isEmpty())
frontPtr = newNodePtr; // The queue was empty
else
backPtr->setNext(newNodePtr); // The queue was not empty
backPtr = newNodePtr; // New node is at back
return true;
} // end enqueue
bool LinkedQueue::dequeue()
{
bool result = false;
if (!isEmpty())
{
// Queue is not empty; remove front
Node* nodeToDeletePtr = frontPtr;
if (frontPtr == backPtr)
{ // Special case: one node in queue
frontPtr = nullptr;
backPtr = nullptr;
}
else
frontPtr = frontPtr->getNext();
// Return deleted node to system
nodeToDeletePtr->setNext( nullptr);
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
result = true;
} // end if
return result;
} // end dequeue
bool LinkedQueue:: isEmpty()
{
return (frontPtr == nullptr );
}
int LinkedQueue:: peekFront() const
{
return frontPtr->getItem();
}
LinkedQueue::LinkedQueue()
{
frontPtr = nullptr;
backPtr = nullptr;
}
LinkedQueue::LinkedQueue( const LinkedQueue& aQueue) :
frontPtr(aQueue.frontPtr)
{
} // end copy constructor
LinkedQueue::~LinkedQueue()
{
} // end destructor
timeLeftOnCar =! 0 is the same as timeLeftOnCar = !0, which is timeLeftOnCar = 1, which is always true.
You wanttimeLeftOnCar != 0 or timeLeftOnCar > 0.
Related
i have an assigment where i have to work with singly linked list using oop. I got stuck mostly on the sortedInsert function. I am assuming it will be some mistake with using pointers but I can't figure it out. And the program crashes after entering the user input in the for loop in initializeList function it might be because of the sortedInsert function but maybe it's something else.
Can someone help me figure out where am I getting it worng?
Here is the code:
#include <iostream>
using namespace std;
class Item{
private:
int m_value;
Item* m_next;
public:
Item(int val){
m_value = val;
m_next = NULL;
};
int getValue(){ return this->m_value; };
Item* getNext() { return this->m_next; };
void setValue(int val){ m_value = val; };
void setNext(Item* nxt){ m_next = nxt; };
};
class IntList{
private:
Item* m_front = NULL;
Item* m_end;
int m_size = 0;
void bump_up(int m_size){ m_size++; };
void bump_down(int m_size){ m_size--; };
public:
IntList(){ m_front = NULL; };
Item* getFirst(){ return this->m_front; };
//int getValueFirst(){ return this->firstItem->getValue(); };
~IntList();
void sortedInsert(Item* first, int val){
Item* newItem = new Item(val);
Item* current;
if(first == NULL || (first)->getValue() >= newItem->getValue()){
newItem->setNext(first);
first = newItem;
}
else{
current = first;
while(current->getNext() != NULL && current->getNext()->getValue() < newItem->getValue()){
current = current->getNext();
}
newItem->setNext(current->getNext());
current->setNext(newItem);
}
bump_up(m_size);
}
//print
void display(){
Item* p = m_front;
cout << "(" << m_size << ")";
while(p != NULL){
cout << p->getValue() << " ";
p = p->getNext();
}
cout << endl;
}
void initializeList(IntList* list){
int x, i;
cout << "Insert list size: ";
cin >> x;
cout << "Insert " << x << " numbers, which will be put in the list:";
for(i = 0; i <= x; i++){
int a;
cin >> a;
list->sortedInsert(list->getFirst(), a);
}
//cout << endl;
}
int main()
{
IntList* list = new IntList();
initializeList(list);
list->display();
return 0;
}
my problem is it's Process returned -1073741819. What shall i do to compile it faster?
#include "Queue.h"
#include <iostream>
Queue::Queue()
{
topPtr = NULL;
tailPtr = NULL;
}
bool Queue::isEmpty()
{
if(topPtr == NULL && tailPtr == NULL)
return true;
else
return false;
}
void Queue::enqueue(int data)
{
Node *newNodePtr = new Node;
newNodePtr->data = data;
if(topPtr == NULL)
{
topPtr = tailPtr = newNodePtr;
tailPtr->nextPtr = NULL;
}
else
{
tailPtr->nextPtr = newNodePtr;
tailPtr = newNodePtr;
tailPtr->nextPtr = NULL;
}
}
int Queue::dequeue()
{
if (isEmpty())
{
cout << "empty" <<endl;
}
else
{
int dataToReturn = topPtr->data;
Node *nodeToDeletePtr = topPtr;
dataToReturn = nodeToDeletePtr->nextPtr;
topPtr = topPtr->nextPtr;
delete nodeToDeletePtr;
return dataToReturn;
}
}
#ifndef QUEUE_H
#define QUEUE_H
struct Node
{
int data;
Node *nextPtr;
};
class Queue
{
public:
Queue();
void enqueue(int data);
int dequeue();
bool isEmpty();
private:
Node *topPtr;
Node *tailPtr;
};
#endif
#include <iostream>
#include <string.h>
#include <cstdlib>
#include "Queue.h"
using namespace std;
int main(int argc, char const *argv[])
{
Queue integers;
string seriesIntegers;
cout << "Enter integers: ";
getline(cin, seriesIntegers);
char *seriesIntegersCStr = new char[seriesIntegers.length() + 1];
strcpy(seriesIntegersCStr, seriesIntegers.c_str());
char *tokens = strtok(seriesIntegersCStr, " ");
while(tokens != NULL)
{
integers.enqueue(atoi(tokens));
tokens = strtok(NULL, " ");
}
while(!integers.isEmpty())
{
cout << " " << integers.dequeue() << "\n";
}
}
Among the things wrong:
You never reset tailPtr to null during a dequeue operation that emptied the queue.
Due to the first item, your isEmpty member was incorrectly reporting the queue still had data because one of the two conditions (tailPtr == nullptr) was not true, and therefore the queue wasn't "empty" even though it was.
Due to both of the items above, your while-loop in main ran off the end of the queue.
Your dequeue operation has a major control path that returns no value, though you promised in your declaration of returns-int that it would. At a minimum this should throw an exception; ideally it should not be allowed in the first place.
Queue should self-clean on destruction rather than leaking the node chain in a non-empty state.
As a course of adding a custom destructor to clean dynamic content, Queue should be rule-of-three compliant by either defining proper operations for copy-ctor and assignment operators, or specifying them as deleted (as I did below)
Fixing all of that, and a few other modifications, including entering the real world of modern C++ to utilize a string stream to read the integers rather than strtok and leaked memory as you were before, see the code below:
#include <iostream>
#include <sstream>
#include <string>
struct Node
{
int data;
Node *nextPtr;
Node(int val, Node *next = nullptr)
: data(val)
, nextPtr(next)
{
}
};
class Queue
{
public:
Queue();
virtual ~Queue();
Queue(const Queue&) = delete;
Queue& operator =(const Queue&) = delete;
void enqueue(int data);
int dequeue();
bool isEmpty() const;
private:
Node *topPtr;
Node *tailPtr;
};
Queue::Queue()
: topPtr(nullptr)
, tailPtr(nullptr)
{
}
Queue::~Queue()
{
while (topPtr)
dequeue();
}
bool Queue::isEmpty() const
{
return topPtr == nullptr;
}
void Queue::enqueue(int data)
{
Node *newNodePtr = new Node(data);
if (topPtr == NULL)
{
topPtr = newNodePtr;
}
else
{
tailPtr->nextPtr = newNodePtr;
}
tailPtr = newNodePtr;
}
int Queue::dequeue()
{
if (isEmpty())
{
throw std::runtime_error("'dequeue' called on an already-empty queue");
}
// get top data
int dataToReturn = topPtr->data;
// advance top, retaining pointer to old node
Node *tmp = topPtr;
topPtr = topPtr->nextPtr;
// now delete the node
delete tmp;
// and reset tail if top hit end-of-queue
if (topPtr == nullptr)
tailPtr = nullptr;
// finally, return data
return dataToReturn;
}
int main()
{
std::cout << "Enter integers: ";
std::string line;
if (getline(std::cin, line) && !line.empty())
{
Queue integers;
std::istringstream iss(line);
int value;
while (iss >> value)
integers.enqueue(value);
while (!integers.isEmpty())
std::cout << integers.dequeue() << '\n';
}
}
Input
1 2 3 4 5
Output
Enter integers: 1 2 3 4 5
1
2
3
4
5
The following is a new programmer's attempt at a Queue. It seg faults in the Push() function, when I try to print the data in the first node. Looks like front_ptr is not actually getting set in head_insert. What am I doing wrong here, is this a completely wrong approach?
Thanks.
#include <cstdlib>
#include <iostream>
using namespace std;
class node {
public:
typedef double data_type;
node(data_type init_data = 0, node * init_next = NULL) {
data = init_data;
next_node = init_next;
}
void set_data(data_type new_data) { data = new_data; }
void set_next(node * new_next) { next_node = new_next; }
data_type get_data() { return data; }
node * get_next() { return next_node; }
private:
data_type data;
node * next_node;
};
void head_insert(node::data_type val, node* head_ptr) {
node* insert_ptr = new node(val, head_ptr);
head_ptr = insert_ptr;
}
void list_insert(node::data_type val, node* prev_ptr) {
node* insert_ptr = new node(val, prev_ptr->get_next());
prev_ptr->set_next(insert_ptr);
}
void head_remove(node* head_ptr) {
node* remove_ptr = head_ptr;
head_ptr = head_ptr->get_next();
delete remove_ptr;
}
void list_remove(node * prev_ptr) {
node* remove_ptr = prev_ptr->get_next();
prev_ptr->set_next(remove_ptr->get_next());
delete remove_ptr;
}
void list_clear(node* head_ptr) {
while (head_ptr != NULL) {
head_remove(head_ptr);
}
}
class queue {
public:
queue() {
size = 0;
front_ptr = NULL;
rear_ptr = NULL;
}
//~queue() {}
bool empty() { return (size == 0);}
void push(node::data_type val) {
if (empty()) {
head_insert(val, front_ptr);
cout << "Here: " << front_ptr->get_data() << endl;
rear_ptr = front_ptr;
}
else {
list_insert(val, rear_ptr);
}
size++;
}
void pop() {
if (!empty()) {
head_remove(front_ptr);
size--;
}
}
private:
node* front_ptr;
node* rear_ptr;
int size;
};
int main() {
cout << "START" << endl;
double testVal = 1;
queue* qList = new queue();
qList->push(testVal);
cout << "END" << endl;
return 0;
}
Any help is greatly appreciated.
Your front_ptr remains null pointer in push, because head_insert accepts it by value. Dereferencing null pointer then crashes the program. Make parameters that you want to be modified by a function reference parameters like void head_insert(node::data_type val, node*& head_ptr).
Also, you can avoid crash of null pointer dereferencing by checking it before, for example like that:
cout << "Here: " << (front_ptr ? front_ptr->get_data() : 0./0.) << endl;
This question already has answers here:
How come a non-const reference cannot bind to a temporary object?
(11 answers)
Closed 5 years ago.
So, i'm attempting to implement this Queue using my LinkedList that I previously created. I've provided the code for both classes. Currently, I'm work on attempting to get pop and push to work without changing the function prototype (it's for an assignment).
When looking specifically at peek(I haven't quite finished pop), for some reason, when I run the code, I get strange pointer error.
Error C2440 'default argument': cannot convert from 'int' to 'int &'
I'm not sure exactly what that means in this context. The function is suppose to look at the object at the top of the queue without removing it, and return true or false based upon if the operation was successful or not.
Here is the info for QUEUE.
#ifndef _QUEUE_H
#define _QUEUE_H 1
#include "QueueInterface.h"
#include "LinkedList.hpp"
template <typename T>
class Queue : public QueueInterface<T>
{
protected:
LinkedList<T> _list;
int count;
public:
unsigned size() const
{
return count;
}
bool push(const T& val = T{})
{
_list.push(val);
count++;
return true;
}
bool empty() const
{
return _list.isEmpty();
}
bool pop(T& val = T{})
{
return true;
}
bool peek(T& val = T{}) const
{
std::cout << _list.last() << std::endl;
return true;
}
void clear()
{
_list.clear();
}
int search(const T& target = T{}) const
{
return _list.search(target);
}
//
// Internal consistency check
//
void toString()
{
_list.toString();
}
public:
virtual bool check() const
{
return _list.check();
}
};
#endif
Here is Linked List.
#ifndef _LINKED_LIST_GUARD
#define _LINKED_LIST_GUARD 1
#include <iostream>
#include "ListInterface.h"
template <typename T>
class LinkedList : public ListInterface<T>
{
public:
int count = 0;
LinkedList()
{
_head = new Node;
_tail = new Node;
_head->_next = _tail;
}
private:
//
// Private node class to facilitate linked list
//
class Node
{
public:
T _data;
Node* _next;
// Constructor: default
Node(T d = T{}, Node* n = nullptr) : _data(d), _next(n) {}
~Node() { _next = nullptr; }
};
//
// Prevent copying and assigning
//
LinkedList(const LinkedList& rhs) {}
const LinkedList& operator=(const LinkedList& rhs) {}
public:
//
// LinkedList instance variables; we use dummy head and tail nodes in this implementation
unsigned _size;
Node* _head;
Node* _tail;
// Returns the first element in the list
T& first() const
{
return _head->_next->_data;
}
// Adds an item to the LEFT side of the linked list
void push(const T& x)
{
// Creates a new node with the user input data.
Node* current = new Node;
current->_data = x;
current->_next = _head->_next;
_head->_next = current;
count++;
}
// ASK ABOUT
T& operator[](unsigned n)
{
int position = 1;
if (n != count)
{
throw("Invalid Position");
}
for (Node* current = _head->_next; current != _tail; current = current->_next, position++)
{
if (position == n)
{
return current -> _data;
}
}
}
void clear()
{
do
{
pop();
} while (count != 0);
}
bool contains(const T& target) const
{
for (Node* current = _head->_next; current != _tail; current = current->_next)
{
if (current->_data == target)
return true;
}
return false;
}
bool pop()
{
if (_head->_next == _tail)
{
std::cout << "unable to pop, list is empty";
return false;
}
if (_head->_next != _tail)
{
Node* deleteNode = _head->_next;
_head->_next = _head->_next->_next;
delete deleteNode;
count--;
return true;
}
return false;
}
T& last() const
{
if (_head->_next == _tail)
{
std::cout << "LIST IS EMPTY" << std::endl;
}
if (_head->_next != _tail)
{
for (Node* current = _head->_next; current != _tail; current = current->_next)
{
if (current->_next == _tail)
return current->_data;
}
}
}
// ASK ABOUT
int search(const T& target = T{}) const
{
int position = 1;
for (Node* current = _head->_next; current != _tail; current = current->_next)
{
if (current->_data == target)
{
return position;
}
else position++;
}
return -1;
}
bool isEmpty() const
{
if (_head->_next == _tail)
{
return true;
}
return false;
}
unsigned size() const
{
return count;
}
bool remove(const T& target)
{
Node* deleteNode = nullptr;
Node* trailer = _head;
Node* current = _head->_next;
while (current != _tail && current-> _data != target)
{
trailer = current;
current = current->_next;
}
if (current->_data == target)
{
deleteNode = current;
current = current->_next;
trailer->_next = current;
delete deleteNode;
count--;
return true;
}
else
std::cout << "unable to remove, item not in list" << std::endl;
return false;
}
//FOR TESTING
void toString()
{
for (Node* current = _head->_next; current != _tail; current = current->_next)
{
std::cout << current->_data << std::endl;
}
}
//
// Internal consistency check
//
public:
virtual bool check() const
{
bool sizeConsistent = isSizeConsistent();
bool headTailConsistent = isEndConsistent();
if (!sizeConsistent) std::cerr << "Size inconsistent" << std::endl;
if (!headTailConsistent) std::cerr << "Head / Tail inconsistent" << std::endl;
return sizeConsistent && headTailConsistent;
}
//
// Stated size is accurate to the entire list
//
bool isSizeConsistent() const
{
int count = 0;
for (Node* current = _head->_next; current != _tail; current = current->_next)
{
count++;
}
return size() == count;
}
//
// Checks that the head and tail are defaulted properly and the
// respective next pointers are appropriate.
//
bool isEndConsistent() const
{
if (_head->_data != T{}) return false;
if (_tail->_data != T{}) return false;
if (_head->_next == nullptr) return false;
if (_tail->_next != nullptr) return false;
if (isEmpty() && _head->_next != _tail) return false;
if (!isEmpty() && _head->_next == _tail) return false;
return true;
}
};
#endif
And finally, here is my main. The top portion is to test the functionality for LinkedList. The bottom portion is what I was working with to test queue.
#include "Queue.hpp"
#include "LinkedList.hpp"
#include <string>
#include <iostream>
int main()
{
LinkedList<int> list;
LinkedList<int> listEmpty;
Queue<int> list2;
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
list.remove(1);
std::cout << "List contains 4? " << list.contains(4) << std::endl;
std::cout << "List empty? " << list.isEmpty() << std::endl;
std::cout << "List size: " << list.size() << std::endl;
std::cout << "Last in list? " << list.last() << std::endl;
std::cout << "What is in position 4? " << list[4] << std::endl;
std::cout << "Search " << list.search(10) << std::endl;
//std::cout << "3 is in position " << list.search() << std::endl;
std::cout << " " << std::endl;
list.toString();
list.clear();
std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
list.push(4);
list.toString();
std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
std::cout << "QUEUE STUFF" << std::endl;
std::cout << "///////////////////////////////////////////////////////////////////////////////" << std::endl;
list2.push(1);
list2.push(2);
list2.push(6);
list2.push(3);
list2.push(4);
list2.push(5);
std::cout << "Queue empty? " << list2.empty() << std::endl;
std::cout << "Queue size: " << list2.size() << std::endl;
std::cout << "First in Queue? " << list2.peek() << std::endl;
std::cout << "What position is 6 in? : " << list2.search(6) << std::endl;
list2.toString();
std::cout << " " << std::endl;
system("pause");
I guess my question is this, what steps can I take to go about fixing this particular function?
Thanks in advance!
The problem with your code is that peek, as you said, should not modify the Queue and neither take any parameter because it merely looks at the top of the structure and returns either true or false.
So a solution is to remove the parameter in peak as follows and everything compiles and runs.
bool peek() const
{
std::cout << _list.last() << std::endl;
return true;
}
Specifically, the error you get is because you cannot assign to a non-const lvalue reference an rvalue reference.
This is exactly what you are doing in T& val = T{}. T{} is an rvalue and clearly, val is a non-const reference to T.
You can try using bool peek(const T& val = T{}) const and see by yourself that everything compiles fine.
I am creating a priority queue that utilizes a binary search tree for my Data Structures class. But when I attempt to output the queue I always get 0. I have looked over my DeleteLargest and Dequeue member function but I can't find the mistake
Test.cpp
#include <iostream>
#include "CTree.h"
#include "PriorityQueueBST.h"
using namespace std;
int main()
{
int num, input, output;
cout << "Enter number of elements: ";
cin >> num;
PriorityQueueBST p;
for (int x = 0; x < num; x++)
{
cout << "Enter number " << x + 1
<< " of " << num << ": ";
cin >> input;
p.Enqueue(input);
}
for (int y = 0; y < num; y++)
{
cout << "Outputting number " << y + 1
<< " of " << num << ": ";
if(p.IsEmpty())
{
break; //we are done (this is an error!)
}
output = p.Dequeue();
cout << output << endl;
}
system("pause");
return 0;
//CTree* tr = new CTree();
//
//for (int i = 0; i < 3; i++)
// tr->Add();
//tr->View();
//system("pause");
//return 0;
}
BST Declaration file
//#ifndef CTREE_H
//#define CTREE_H
//using namespace std;
struct TreeNode
{
int info;
TreeNode* leftLink;
TreeNode* rightLink;
};
class CTree
{
private:
void AddItem( TreeNode*&, TreeNode*);
void DisplayTree(TreeNode*);
void Retrieve(TreeNode*&, TreeNode*,bool&);
void Destroy(TreeNode*&);
public:
CTree();
~CTree();
void Add();
void View();
bool IsEmpty();
int DeleteLargest(TreeNode*&);
TreeNode *tree;
};
//#endif
BST Implementation file
#include <iostream>
#include <string>
using namespace std;
#include "CTree.h"
CTree::CTree()
{
tree = NULL;
}
CTree::~CTree()
{
Destroy(tree);
}
void CTree::Destroy(TreeNode*& tree)
{
if (tree != NULL)
{
Destroy(tree->leftLink);
Destroy(tree->rightLink);
delete tree;
}
}
bool CTree::IsEmpty()
{
if(tree == NULL)
{
return true;
}
else
{
return false;
}
}
void CTree::Add()
{
TreeNode* newPerson = new TreeNode();
/*cout << "Enter the person's name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.getline(newPerson->name, 20);*/
/* cout << "Enter the person's contribution: ";
cin >> newPerson->info;*/
/*bool found = false;*/
newPerson->leftLink = NULL;
newPerson->rightLink = NULL;
/*Retrieve(tree, newPerson, found);
if (found)
cout << "info allready entered\n";
else*/
AddItem(tree, newPerson);
}
void CTree::View()
{
if (IsEmpty())
{
cout<<"The list is empy";
}
else
{
DisplayTree(tree);
}
};
void CTree::AddItem( TreeNode*& ptr, TreeNode* newPer )
{
if (ptr == NULL)
{
ptr = newPer;
}
else if ( newPer->info < ptr->info)
AddItem(ptr->leftLink, newPer);
else
AddItem(ptr->rightLink, newPer);
}
void CTree::DisplayTree(TreeNode* ptr)
{
if (ptr == NULL)
return;
DisplayTree(ptr->rightLink);
cout << ptr->info << endl; //cout<<ptr->name<<" "<<"$"<<ptr->info <<endl;
DisplayTree(ptr->leftLink);
}
void CTree::Retrieve(TreeNode*& ptr, TreeNode* newPer, bool& found)
{
{
if (ptr == NULL)
{
found = false; // item is not found.
}
else if ( newPer->info < ptr->info)
{
Retrieve(ptr->leftLink, newPer, found);
}
// Search left subtree.
else if (newPer->info > ptr->info)
{
Retrieve(ptr->rightLink, newPer, found);// Search right subtree.
}
else
{
//newPer.info = ptr->info; // item is found.
found = true;
}
}
}
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
Priority Queue Declaration
//#include <iostream>
//using namespace std;
//#include "SortedLinkedList.h"
#ifndef PRIORITYQUEUESLL__H
#define PRIORITYQUEUESLL__H
class PriorityQueueBST
{
public:
PriorityQueueBST();
~PriorityQueueBST();
void Enqueue(int);
int Dequeue();
bool IsEmpty();
private:
CTree* ourTree;
//sslNode* head;
};
#endif
Priority Queue Implementation
#include <iostream>
using namespace std;
#include "CTree.h"
#include "PriorityQueueBST.h"
PriorityQueueBST::PriorityQueueBST()
{
ourTree = new CTree();
//head = NULL;
}
PriorityQueueBST::~PriorityQueueBST()
{
}
void PriorityQueueBST::Enqueue(int dataToEnter)
{
ourTree->Add();
}
int PriorityQueueBST::Dequeue()
{
//check for empty??
return ourTree->DeleteLargest(ourTree->tree);
}
bool PriorityQueueBST::IsEmpty()
{
return ourTree->IsEmpty();
}
Your output is always 0 because in
int CTree::DeleteLargest(TreeNode*& tr)
{
int largest = 0;;
TreeNode* prev;
TreeNode* cur;
prev = NULL;
cur = tr;
if (tr == NULL)
{
cout << "The tree is empty"<<endl;
}
else if (tr->rightLink == NULL)
{
largest = tr->info;
}
else
{
prev = tr;
tr = tr->rightLink;
DeleteLargest(tr);
}
return largest;
}
you only set largest to something potentially != 0 if tr->rightlink is NULL. Otherwise you recur and set the largest variable local to another invocation of the function. That change is lost when the recursion goes up again, and in the topmost invocation, largest is still 0.
In the last line of the else branch, you should either
largest = DeleteLargest(tr);
or
return DeleteLargest(tr);
Another problem is that, despite its name, deleteLargest doesn't actually delete anything, so with the above, you would still always get the same value.