Below is my code
to create hashtable with key as Char* and value as Function pointer
// hash1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#define SIZE_KEY 16
#define SIZE_VALUE1 64
#define SIZE_VALUE2 16
#define DEFAULT_TABLESIZE 101
using namespace std;
typedef void (*FunctionPtr)();
typedef void (*FunctionPtr1)();
void (*FunctionPtr2)();
void ping(){
cout<<"hello";
}
void refresh(){
cout<<"refresh";
}
typedef struct NODE
{
NODE(char* Key1,FunctionPtr func_ptr)
{
strcpy_s(Key,Key1);
FunctionPtr1 func_ptr1;
func_ptr1=func_ptr;
next = NULL;
}
NODE(){
}
char Key[SIZE_KEY];
FunctionPtr1 func_ptr1[SIZE_VALUE1];
NODE *next;
};
class Hashtable
{
private:
int table_size;
NODE** table;
int size;
long hashString(char* Key);
NODE* find(char* Key);
NODE* current_entry;
public:
int current_index;
Hashtable(int T = DEFAULT_TABLESIZE);//constructor
virtual ~Hashtable();//destructor
bool put(NODE *);
bool get(NODE *);
bool contains(char* Key);
void removeAll();
int getSize();
void initIterator();
bool hasNext();
void getNextKey(char* Key);
friend void disp(NODE *);
};
Hashtable::Hashtable(int T)
{
size = 0;
table_size = T;
table = new NODE*[table_size];
for(int i=0; i<table_size; i++)
{
table[i] = NULL;
}
}
Hashtable::~Hashtable()
{
removeAll();
delete[] table;
}
bool Hashtable::put(NODE *N)
{//start put
if(find(N->Key) != NULL)
{
return false;
}
//NODE* entry = new NODE( N->Key ,*(FunctionPtr *)N->func_ptr1 );
NODE* entry = new NODE( N->Key ,*(FunctionPtr *)N->func_ptr1 );
int bucket = hashString(N->Key);
entry->next = table[bucket];
table[bucket] = entry;
size++;
return true;
}//end put
bool Hashtable::get(NODE* N)
{//start get
NODE* temp = find(N->Key);
if(temp == NULL)
{
*(FunctionPtr *)N->func_ptr1 = refresh;
return false;
}
else
{
*(FunctionPtr *)N->func_ptr1= *(FunctionPtr *)temp->func_ptr1;
return true;
}
}//end get
bool Hashtable::contains(char* Key)
{//start contains
if(find(Key) == NULL)
{
return false;
}
else
{
return true;
}
}//end contains
void Hashtable::removeAll()
{//start removeAll
for(int i=0; i<table_size; i++)
{
NODE* temp = table[i];
while(temp != NULL)
{
NODE* next = temp->next;
disp(temp);
delete temp;
temp = next;
}
}
size = 0;
}//end removeAll
int Hashtable::getSize()
{
return size;
}
NODE* Hashtable::find(char* Key)
{ //start find
int bucket = hashString(Key);
NODE* temp = table[bucket];
while(temp != NULL)
{
if(strcmp(Key, temp->Key) == 0)
{
return temp;
}
temp = temp->next;
}
return NULL;
}//end find
long Hashtable::hashString(char* Key)
{//start hashString
int n = strlen(Key);
long h = 0;
for(int i=0; i<n; i++)
{
//To get almost fair distributions of NODEs over the array
h = (h << 3) ^ Key[i];
}
return abs(h % table_size );
}//end hashString
void Hashtable::initIterator()
{//start initIterator
current_entry = NULL;
current_index = table_size;
for(int i=0; i<table_size; i++)
{
if(table[i] == NULL)
{
continue;
}
else
{
current_entry = table[i];
current_index = i;
break;
}
}
}//end initIterator
bool Hashtable::hasNext()
{
if(current_entry == NULL)
{
return false;
}
else
{
return true;
}
}
void Hashtable::getNextKey(char* Key)
{
if(current_entry == NULL)
{
Key[0] = '\0';
return;
}
strcpy(Key, current_entry->Key);
if(current_entry->next != NULL)
{
current_entry = current_entry->next;
}
else
{
for(int i=current_index+1; i<table_size; i++)
{
if(table[i] == NULL)
{
continue;
}
current_entry = table[i];
current_index = i;
return;
}
current_entry = NULL;
current_index = table_size;
}
}
void dispAll(Hashtable* hashtable);
int main()
{
char temp1[SIZE_KEY];
Hashtable* hashtable = new Hashtable();
NODE N1("1",ping);
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
// dispAll(hashtable);
strcpy(N1.Key, "314");
*(FunctionPtr *) N1.func_ptr1=refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
/* strcpy(N1.Key, "320");
*(FunctionPtr *) N1.func_ptr1= ping;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding NODE: ";
disp(&N1);
hashtable->put(&N1);
}
strcpy(N1.Key, "768");
*(FunctionPtr *)N1.func_ptr1= refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding node: ";
disp(&N1);
hashtable->put(&N1);
}
strcpy(N1.Key, "756");
*(FunctionPtr *) N1.func_ptr1= refresh;
if(!hashtable->contains(N1.Key))
{
cout << "\nAdding node: ";
disp(&N1);
hashtable->put(&N1);
} */
dispAll(hashtable);
// strcpy(temp1,"314");
// hashtable->remove(temp1);
// cout << "\n\nAfter removing 314:" << endl;
// dispAll(hashtable);
cout << "\n\nDestroying hashtable:" << endl;
delete hashtable;
return 0;
}
void disp(NODE *N1)
{
cout << "\nKey: " << N1->Key << "\nFunction "
<< N1->func_ptr1 << endl;
// FunctionPtr2();
}
void dispAll(Hashtable *hashtable)
{
NODE N1;
cout << "\n\nCurrent nodes in hashtable:" << endl;
hashtable->initIterator();
while(hashtable->hasNext())
{
//cout<<"Current Index === "<<hashtable->current_index;
hashtable->getNextKey(N1.Key);
hashtable->get(&N1);
disp(&N1);
}
}
each time data is written in hash table VALUE cointains the same address :(
i want address of particular function that i will send..
Some of the problems may be in struct NODE.
typedef struct NODE
{
NODE(char* Key1,FunctionPtr func_ptr)
{
strcpy_s(Key,Key1);
FunctionPtr1 func_ptr1; // <-- Problem may be here
func_ptr1=func_ptr;
next = NULL;
}
NODE(){
}
char Key[SIZE_KEY];
FunctionPtr1 func_ptr1[SIZE_VALUE1]; // <-- And here
NODE *next;
};
You declared a local func_ptr1 in NODE::NODE(char*, FunctionPtr), and assign the parameter func_ptr to func_ptr1. Thus, func_ptr is assigned to a local variable, not a member variable. And, once the constructor returns, nothing about the function pointer is remembered.
Another problem: why is NODE::func_ptr1 an array of FunctionPtr1? I don't think you intended to store multiple function pointers in one NODE instance.
Related
The code is supposed to do queue functions which I got right.
The only problem I am having is: I am supposed to double the array size to twice its original size once the array gets completely filled.
I have coded for it but still getting garbage values when I try to put in more values than the original array size. So the problem seems to be in the inc() function below:
#ifndef Q_H_
#define Q_H_
#include <iostream>
using namespace std;
template <class elemType>
class arrayQueue
{
int size;
int *array;
int front;
int back;
int count;
public:
arrayQueue(elemType size)
{
this->size = size;
array = new int[size];
front = 0;
back = -1;
count=0;
}
bool isEmpty()
{
return (max()==0);
}
bool isFull() {
return (max()==size);
}
void enqueue(elemType entry)
{
cout << "enqueue " << entry;
if(isEmpty())
{
front = back = 0;
array[back] = entry;
count++;
}
else
{
back = (back+1) % size;
array[back] = entry;
count++;
}
cout << endl;
}
int maxsize()
{
return count;
}
void dequeue() {
cout << "dequeue : " << Front();
if(isEmpty())
{
cout << " error : empty";
}
else if(back == front)
{
back = front = -1;
}
else
{
front = (front+1) % size;
count--;
}
cout << endl;
}
void print()
{
if(isEmpty())
{
cout << "Queue is empty";
}
else
{
for(int i = front; i<count; i++)
{
cout << array[i] << " ";
}
cout << array[back];
}
//cout<<"count is:" <<count<<endl;
cout << endl;
}
int Front()
{
if(front == -1)
{
cout<<"Queue is empty\n";
return -1;
}
return array[front];
}
int Back()
{
if(back==-1)
{
cout<<"Queue is full";
}
return array[back];
}
int max()
{
return count;
cout <<"count: " <<count;
}
void inc()
{
int newsize = this->size*2;
elemType *temp = new elemType[newsize];
for (int i=0; i<this->count;i++)
{
temp[i]=this->array[(front+i) % size];
}
delete [] this->array;
this->array=temp;
this->count=newsize;
// front=array[front]; //0
//front = 0;
//back=count;
}
};
#endif /* Q_H_ */
I would really appreciate help with this.
three small changes:
enqueue method: inc when isFull
if (isFull())
{
inc();
}
print method: print every element from front to back
inc method: copy every element from front to back, and reset front and back index
void inc()
{
int newsize = this->size*2;
elemType *temp = new elemType[newsize];
// ******* IMPORTANT ******
// copy count elements
for (int i = 0; i < count; ++i) {
int index = (front + i) % size;
temp[i] = array[index];
}
front = 0;
back = count - 1;
delete []array;
array=temp;
count=newsize;
}
template <class elemType>
class arrayQueue
{
int size;
int *array;
int front;
int back;
int count;
public:
arrayQueue(elemType size)
{
this->size = size;
array = new int[size];
front = 0;
back = -1;
count=0;
}
bool isEmpty()
{
return (max()==0);
}
bool isFull() {
return (max()==size);
}
void enqueue(elemType entry)
{
cout << "enqueue " << entry;
if(isEmpty())
{
front = back = 0;
array[back] = entry;
count++;
}
else
{
if (isFull()) {
inc();
}
back = (back+1) % size;
array[back] = entry;
count++;
}
cout << endl;
}
int maxsize()
{
return count;
}
void dequeue() {
cout << "dequeue : " << Front();
if(isEmpty())
{
cout << " error : empty";
}
else if(back == front)
{
back = front = -1;
}
else
{
front = (front+1) % size;
count--;
}
cout << endl;
}
void print()
{
if(isEmpty())
{
cout << "Queue is empty";
}
else
{
// ******* IMPORTANT ******
for (int i = 0; i < count; ++i) {
int index = (front + i) % size;
cout << array[index] << " ";
}
}
//cout<<"count is:" <<count<<endl;
cout << endl;
}
int Front()
{
if(front == -1)
{
cout<<"Queue is empty\n";
return -1;
}
return array[front];
}
int Back()
{
if(back==-1)
{
cout<<"Queue is full";
}
return array[back];
}
int max()
{
return count;
cout <<"count: " <<count;
}
void inc()
{
int newsize = this->size*2;
elemType *temp = new elemType[newsize];
// ******* IMPORTANT ******
// copy count elements
for (int i = 0; i < count; ++i) {
int index = (front + i) % size;
temp[i] = array[index];
}
front = 0;
back = count - 1;
delete []array;
array = temp;
count = newsize;
}
};
Since you move elements to the beginning of the newly allocated array, inc needs to update front and back to refer to their respective new positions.
Also, you're updating count to be the new size instead of size.
I have made a C++ program for a binary tree. But the terminal is not asking the statement for inputting the direction for where the elements are to be placed.
Also when I replace the statement from " node *temp = new node " to "node *temp=NULL" the program stops working .
#include <iostream>
#include <cstring>
using namespace std;
class node {
int data;
node * left;
node * right;
public:
node * level_order(node * first);
node * create_bt(node * first);
void display(node * first);
};
//node *first=NULL;
node * node::create_bt(node * first) {
node * temp = new node;
int ele;
//char dir;
cout << "\n Enter data ";
cin >> ele;
temp->data = ele;
temp->left = NULL;
temp->right = NULL;
if (first == NULL) {
temp = first;
return first;
} else {
char dir[20];
cout << "\n Enter the direction ";
cin >> dir;
node * cur = first;
int j = 0;
while (dir[j] != '\0') {
if (dir[j] == 'l') {
cur = cur->left;
}
if (dir[j] == 'r') {
cur = cur->right;
}
j++;
}
cur = temp;
return first;
}
}
void node::display(node * first) {
if (first == NULL)
return;
cout << "\n " << first->data;
display(first->left);
display(first->right);
}
int main() {
int n;
node s;
node * first = NULL;
cout << "\n No of elements ";
cin >> n;
for (int i = 0; i < n; i++) {
first = s.create_bt(first);
}
s.display(first);
return 0;
}
first=s.create_bt(first); does not changes state, from NULL to 'l' or 'r'. You have to change that.
node*node::create_bt(node *first)
{
node *temp=new node;
int ele;
//char dir;
cout<<"\n Enter data ";
cin>>ele;
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
char dir[20];
cout<<"\n Enter the direction ";
cin>>dir;
if(first==NULL)
{
temp=first;
return first;
}
else
{
node*cur=first;
int j=0;
while(dir[j]!='\0')
{
if(dir[j]=='l')
{
cur=cur->left;
}
if(dir[j]=='r')
{
cur=cur->right;
}
j++;
}
cur=temp;
return first;
}
}
I believe you re looking something like this. This is a basic binary tree, i had to make a basic one in order to understand how it works and how it chooses left and right. I make a class inside a class, in order to have access to my data members (node class, int data, *left , *right) and have them at the same time protected, all-in-one. As you can see "newnode" just creates a node and NULL s the pointers. Thats it. "Find" searches and finds a node with a current key, and returns it when exits. All the rest, i guess, you can understand them, as they are prety much the same with your code. The only thing you have to do is to define, when you want to direct the node you want. REMINDER: You have to find a way to utilize it, so the leafs will not end far-left or far-right.("Enter the direction"). I hope i helped you understand.
#include <iostream>
#include <conio.h>
using namespace std;
class mybTree {
class node {
public:
int data;
node * left;
node *right;
};
node *root;
node *newnode(int num){
node *newnode1;
newnode1 = new (nothrow) node;
newnode1->data = num;
newnode1->left = NULL;
newnode1->right = NULL;
return newnode1;
}
public:
node *find (int key) {
node *current;
current = root;
while (current->data !=key){
if (key<current->data){
current = current->left;
} else {
current = current->right;
}
if (current == NULL){
return NULL;
}
}
return NULL;
}
void display (node *ptr);
void display_tree();
bool insert(int num);
void post_order_delete(node *ptr);
mybTree();
~mybTree();
};
int main(){
char ch = ' ';
int a;
mybTree mybTree1;
while (ch !='0'){
cout << "0->Exit"<<endl<< "1-> add"<<endl<< "2-> find" <<endl<<"3-> Show me the tree\n";
ch = getch();
switch (ch) {
case '0':
break;
case '1':
cout << "number";
cin >> a;
if (!mybTree1.insert(a)){
cout << "Not enough memory" << endl;
}
break;
case '2' :
cout << "Number:" ;
cin >> a;
if (mybTree1.find(a)!=NULL) {
cout << "Found" << endl;
} else {
cout << "Not existed" << endl;
}
break;
case '3':
mybTree1.display_tree();
cout<<endl;
break;
default:
cout << "Wrong Message";
break;
}
}
return 0;
}
void mybTree::display(node *ptr) {
if (ptr == NULL){
return;
}
display(ptr->left);
cout << ptr->data<<endl;
display(ptr->right);
}
void mybTree::display_tree() {
//Displays the Tree
display(root);
}
bool mybTree::insert(int num) {
//It inserts a node. Desides left or right.
node *next,*current,*ptr;
int isleft;
next = current = root;
ptr = newnode(num);
if (ptr == NULL) {
return false;
}
if (root == NULL) {
root = ptr;
return true;
}
while (1){
if (num < current->data){
next = current->left;
isleft = 1;
} else {
next = current->right;
isleft = 0;
}
if (next == NULL){
if (isleft){
current->left = ptr;
} else {
current->right = ptr;
}
return true;
}
current=next;
}
return false;
}
void mybTree::post_order_delete(node *ptr) {
//deletes the node. Usefull for destructor
if (ptr == NULL){
return;
}
post_order_delete(ptr->left);
post_order_delete(ptr->right);
cout << ptr->data;
delete ptr;
}
mybTree::mybTree() {
//Constructor
root = NULL;
}
mybTree::~mybTree() {
//Destructor
post_order_delete(root);
root = NULL;
}
I tried to implement BFS for graphs using link list but i have some issues with it, using a queue it only displays the nodes of that origin and not after it. The answer should be 2031 but i only get 203.
The code is below:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <queue>
using namespace std;
class linkListNode
{
public:
linkListNode *next;
int destination;
bool visited;
linkListNode()
{
next = NULL;
destination =0;
visited=false;
}
};
class linkList
{
public:
linkListNode *head;
linkList()
{
head = NULL;
}
// append type insert
void insert(int value)
{
linkListNode *temp2 = new linkListNode;
temp2->destination = value;
temp2->next = NULL;
linkListNode *nodePtr = new linkListNode;
if (head == NULL)
{
head = temp2;
temp2->next = NULL;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = temp2;
}
}
void display()
{
linkListNode *temp = new linkListNode;
temp = head;
while (temp)
{
cout << temp->destination << " --> ";
temp = temp->next;
}
cout << endl;
}
int size()
{
linkListNode *temp = head;
int sizer = 0;
while (temp)
{
sizer++;
temp = temp->next;
}
return sizer;
}
};
class edge
{
public:
int origin;
linkList final;
bool visited;
edge()
{
//origin = NULL;
//cost=0;
visited=false;
}
};
class graph
{
private:
vector <edge> vectorOfEdges;
int vertices;
public:
graph(int v)
{
vertices = v;
vectorOfEdges.clear();
}
void addRoute(int ori, int dest)
{
int counter = 0;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin== ori)
{
counter = 1; // means element was present in the list
e.final.insert(dest);
}
vectorOfEdges[i] = e;
}
if (counter == 0) // when counter is set to zero, this means that the element was not found in the vector and needs to be pushed
{
edge e;
e.origin = ori;
e.final.insert(dest);
vectorOfEdges.push_back(e);
}
}
void printGraph()
{
edge e;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
e = vectorOfEdges[i];
cout << e.origin << ":- ";
e.final.display();
cout << endl;
}
}
int sizeOfEdge(edge e)
{
int x = e.final.size() + 1;
return x;
}
int max(int one, int two)
{
if (one > two)
{
return one;
}
else
{
return two;
}
}
void BFS(int start)
{
edge e;
queue <int> q;
int save_index=0;
for (int i=0;i<vectorOfEdges.size();i++)
{
e=vectorOfEdges[i];
if (e.origin == start)
{
save_index=i;
q.push(e.origin);
e.visited=true;
break;
}
}
while (!q.empty())
{
int x=q.front();
cout << x << " " ;
q.pop();
linkListNode *l = e.final.head;
while (l)
{
if (l->visited == false)
{
q.push(l->destination);
l->visited=true;
l=l->next;
}
else
{
l=l->next;
}
}
}
}
};
int main()
{
graph g(4);
g.addRoute(0, 1);
g.addRoute(0, 2);
g.addRoute(1, 2);
g.addRoute(2, 0);
g.addRoute(2, 3);
// g.printGraph();
//cout << "Following is Breadth First Traversal (starting from vertex 2) \n";
g.BFS(1);
}
Your code is only running for the node that you have provided as the starting value for your BFS traversal.
void BFS(int start)
{
queue<int> q;
bool startFound = false;
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == start)
{
q.push(e.origin);
check.push_back(e.origin);
e.visited = true;
startFound = true;
break;
}
}
if (!startFound)
{
cout << "Start vertex not found in the graph" << endl;
return;
}
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == x)
{
linkListNode *l = e.final.head;
while (l != NULL)
{
bool found = false;
if (l->visited == false)
{
l->visited = true;
for (int i = 0; i < check.size(); i++)
{
if (check[i] == l->destination)
{
found = true;
break;
}
}
if (found == false)
{
check.push_back(l->destination);
q.push(l->destination);
}
}
l = l->next;
}
}
}
}
}
Instead, do this to run it for every node.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define LOWERCASE_ALPHABET_SiZE 26
typedef int (*ptr) (char );
inline int charToIndex(char a) { return a - 'a'; };
class trienode
{
private:
vector< trienode* > child;
bool leaf;
public:
trienode(int );
~trienode();
void initialiseChild(int i);
trienode* getChild(int i);
void setLeaf() { leaf = true; };
bool isLeaf() { return leaf; };
};
trienode::trienode(int size)
{
for(int i = 0; i < size; i++)
{
child.push_back(NULL);
}
leaf = false;
}
trienode::~trienode()
{
for(int i = 0; i < child.size(); i++)
{
delete child.at(i);
child.at(i) = NULL;
}
}
void trienode::initialiseChild(int i)
{
child.at(i) = new trienode(child.size());
}
trienode* trienode::getChild(int i)
{
return child.at(i);
}
class trie
{
private:
trienode* root;
ptr toIndex;
public:
trie(int , ptr );
~trie();
void insert(const string& ref);
bool search(const string& ref);
};
trie::trie(int size, ptr toIndex) : toIndex(toIndex), root(new trienode(size)) { }
trie::~trie()
{
cout << "In destructor trie" << endl;
delete root;
root = NULL;
}
void trie::insert(const string& ref)
{
int size = ref.size();
trienode* root = root;
for(int i = 0; i < size; i++)
{
int index = toIndex(ref[i]);
if(root->getChild(index) == NULL) // crashing in getChild()
{
root->initialiseChild(index);
}
root = root->getChild(index);
}
root->setLeaf();
}
bool trie::search(const string& ref)
{
trienode* root = root;
int size = ref.size();
for(int i = 0; i < size && root != NULL; i++)
{
int index = toIndex(ref[i]);
if((root = root->getChild(index)) == NULL)
{
break;
}
}
return (root != NULL && root->isLeaf());
}
int main(int argc,char* argv[])
{
trie* altrie = new trie(LOWERCASE_ALPHABET_SiZE, charToIndex);
int n;
string temp;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> temp;
altrie->insert(temp);
}
int k;
for(int i = 0; i < k; i++)
{
cin >> temp;
if(altrie->search(temp))
{
cout << temp << " exists in the trie" << endl;
}
else
{
cout << temp << " doesn`t exist in the trie" << endl;
}
}
return 0;
}
I am creating Trie by supplying no of children it can have in each level and function pointer to convert the given character to index. After that I am Creating the root node of trie and when I`m inserting the first string it is getting Segmentation Fault in getChild Function
First things first explain me the reason behind the crash.
Explain me how I can improve the implementation of trie.
You are using the same name for member and local variables, like this:
trienode* root = root;
The compiler cannot tell the diffirence between the local root and trie::root so you are assigning it to itself.
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.