I'm trying to implement a stack using a linked list and class template. I'm not getting any compiler errors but my logic may be wrong, kind of lost. I had a working program in just a single file only using a struct so I had difficulties with translating it over using multiple files and template classes. I will also include my single file cpp below, hopefully it helps. Any help will be greatly appreciated. I have a header.h file, functions.cpp and main. cpp.
Header.h
#define STACK_H
#include <iostream>
using namespace std;
//to implement a stack using linked list
template<class T>
class node{
public:
T data;
node<T>*next;
};
template<class T>
class stack{
private:
node<T> *item;
node<T> *top;
public:
stack(); // constructor
void push( node<T> *); // to insert an item to the stack
void pop(); // to remove an item from the stack
void display(); // to display the stack elements on screen
node<T> *newnode(int );
};
#include "functions.cpp"
#endif
functions.cpp
#include <iostream>
#include "header.h"
#ifndef FUNCTIONS
#define FUNCTIONS
using namespace std;
template<class T>
stack <T> :: stack(){
node<T> *top = NULL;
}
template<class T>
void stack <T> :: push(node<T> * q){
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
template<class T>
void stack <T> :: pop(){
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
item = top;
top = top->next;
delete(item);
}
}
template<class T>
void stack <T> :: display(){
node<T> *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
template<class T>
node<T> * stack <T> :: newnode(int x)
{
item = new node<T>;
item->data = x;
item->next = NULL;
return(item);
}
#endif
main.cpp
#include<iostream>
#include "header.h"
using namespace std;
int main()
{
int ch, x;
stack <int> myStack;
node<int> *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = myStack.newnode(x);
myStack.push( nptr);
}
else if (ch == 2)
{
myStack.pop();
}
else if (ch == 3)
{
myStack.display();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}
Single file working program
struct nodeType
{
int data;
nodeType *next;
};
nodeType *top = NULL;
nodeType *p;
nodeType* newnode(int x)
{
p = new nodeType;
p->data = x;
p->next = NULL;
return(p);
}
void push(nodeType *q)
{
if (top == NULL)
top = q;
else
{
q->next = top;
top = q;
}
}
void pop() {
if (top == NULL) {
cout << "Stack is empty";
}
else {
cout << "Popped element is " << top->data;
p = top;
top = top->next;
delete(p);
}
}
void printStack()
{
nodeType *q;
q = top;
if (top == NULL) {
cout << "Stack is empty!!";
}
else {
while (q != NULL)
{
cout << q->data << " ";
q = q->next;
}
}
}
int main()
{
int ch, x;
nodeType *nptr;
do
{
cout << "\n\n1.Push\n2.Pop\n3.Print Stack\n4.Exit";
cout << "\nPlease enter a function(1-4):";
cin >> ch;
if (ch == 1)
{
cout << "\nEnter data:";
cin >> x;
nptr = newnode(x);
push(nptr);
}
else if (ch == 2)
{
pop();
}
else if (ch == 3)
{
printStack();
}
else cout << "\nInvalid Entry";
} while (ch != 4);
return 0;
}
Related
I don't know if I'm linking wrong but I'm compiling this on linux and I'm getting a LOT of undefined references for my node functions. I'm writing a binary search tree to searches for telephones for class that is due tonight.
bst.cpp
#include "bst.hpp"
BST::BST(void)
{
count = 0;
root = NULL;
}
void BST::insert(long long x, string y)
{
Node *newnode = new Node(x, y);
Node *temp;
if (count == 0)
{
root = newnode;
count++;
}
else
{
while(temp->getleft() != NULL && temp->getright() != NULL)
{
if(newnode->getnum() < temp->getnum())
{
temp = temp->getleft();
}
else
{
temp = temp->getright();
}
}
if (newnode->getnum() < temp->getnum())
{
temp->setleft(newnode);
}
else
{
temp->setright(newnode);
}
}
}
Node * BST::getroot(void)
{
return root;
}
Node* BST::delete_node(Node *troot, long long key)
{
if (count == 0)
{
return troot;
}
else if(key < troot->getnum())
{
delete_node(troot->getleft(), key);
}
else if (key > troot->getnum())
{
delete_node(troot->getright(), key);
}
else
{
if(troot->getleft() == NULL && troot->getright() == NULL)
{
delete troot;
troot == NULL;
}
else if(troot->getright() == NULL)
{
Node *temp = troot;
troot = troot->getleft();
delete temp;
}
else if(troot->getleft() == NULL)
{
Node *temp = troot;
troot = troot->getright();
delete temp;
}
}
return troot;
}
void BST::preverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
preverse(troot->getleft());
preverse(troot->getright());
}
void BST::postverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
postverse(troot->getleft());
postverse(troot->getright());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
}
void BST::inverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
inverse(troot->getleft());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
inverse(troot->getright());
}
void BST::search(Node* troot, long long key)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
if(key == troot->getnum())
{
cout << troot->getname();
}
search(troot->getleft(), key);
search(troot->getright(), key);
}
bst.hpp
#include "node.hpp"
#ifndef bst_hpp
#define bst_hpp
class BST
{
Node* root;
long long count;
public:
BST(void);
void insert(long long x, string y);
Node* getroot(void);
Node* delete_node(Node* troot, long long key);
void preverse(Node* troot);
void postverse(Node* troot);
void inverse(Node* troot);
void search(Node* troot, long long key);
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
number = 0;
name = "no name";
left = NULL;
right = NULL;
}
Node::Node(long long t, string n)
{
number = t;
name = n;
left = NULL;
right = NULL;
}
Node * Node::getleft(void)
{
return left;
}
Node * Node::getright(void)
{
return right;
}
void Node::setleft(Node * ptr)
{
left = ptr;
}
void Node::setright(Node * ptr)
{
right = ptr;
}
long long Node::getnum(void)
{
return number;
}
string Node::getname(void)
{
return name;
}
node.hpp
#ifndef node_hpp
#define node_hpp
#include <string>
#include <iostream>
using namespace std;
class Node
{
long long number;
string name;
Node *left;
Node *right;
public:
Node(void);
Node(long long t, string n);
Node* getleft(void);
Node* getright(void);
void setleft(Node* ptr);
void setright(Node* ptr);
long long getnum(void);
string getname(void);
};
#endif
main.cpp
#include "bst.hpp"
using namespace std;
int main(void)
{
int choice;
long long numin;
string input;
BST phbook;
do
{
cout << "1. Insert a name and number.\n2. Delete using number.\n3. Traverse pre-order\n4. Traverse post-order\n";
cout << "5. Traverse in-order\n6. Search using number.\n6. Exit program\n";
switch(choice)
{
case 1:
cout << "Enter a name\n";
cin.ignore();
getline(cin, input);
cout << "Enter a number\n";
cin >> numin;
phbook.insert(numin, input);
break;
case 2:
cout << "Enter the phone number you'd like to delete.\n";
cin >> numin;
phbook.delete_node(phbook.getroot(), numin);
break;
case 3:
phbook.preverse(phbook.getroot());
break;
case 4:
phbook.postverse(phbook.getroot());
break;
case 5:
phbook.inverse(phbook.getroot());
break;
case 6:
cout << "Enter a phone number to search.\n";
cin >> numin;
phbook.search(phbook.getroot(),numin);
default:
numin=numin;
}
}while(choice >= 1 && choice <= 6);
return 0;
}
To me, nothing looks wrong in linking the files.
Some examples : undefined reference to Node::getnum()
undefined reference to Node::getname()
Check the order of compiled elements:
g++ node.cpp -o node.o bst.cpp -o bst.o main.cpp -o main.o
Result:
./main.o
1. Insert a name and number.
2. Delete using number.
3. Traverse pre-order
4. Traverse post-order
5. Traverse in-order
6. Search using number.
6. Exit program
I've built an AVL Tree out of an old Binary Tree in C++ for practice and it is not working correctly. I think it may not be updating the height of the nodes correctly but I can't figure out the root of the issue ( I'm 90% sure it has to do with the helper functions getHeight, setHeight, getBalance).
Some example test runs..:
adding 6,3,4 causes a Right Rotation it should cause a RL rotation
similarly adding 20,30,25 causes a LL rotation when it should cause a LR rotation
adding 20,30,10,5,6 causes two seperate Right rotations when it should cause a RL rotation
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct intNode {
int data;
intNode * Left;
intNode * Right;
int height;
intNode(int input, intNode * iLeft= NULL, intNode * iRight = NULL) {
data = input;
Left = iLeft;
Right = iRight;
height = 0;
}
};
int getHeight(intNode* temp) {
if (temp == NULL)
return 0;
return temp->height;
}
void setHeight(intNode * temp)
{
int hLeft = getHeight(temp->Left);
int hRight = getHeight(temp->Right);
temp->height = 1 + max(hLeft, hRight);
}
int getBalance(intNode * temp) {
if (temp == NULL) {
return 0;
} else {
return getHeight(temp->Left) - getHeight(temp->Right);
}
}
struct intTree {
intNode * root;
intTree();
void addNode(int input);
void addNode(int input, intNode *& root);
void print();
void print(intNode *input);
intNode * balanceTree(intNode *& sub);
intNode * rotateRight(intNode *& sub);
intNode * rotateLeft(intNode *& sub);
};
void intTree::print(intNode *input) {
if (input != NULL) {
print(input->Left);
cout << input->data << endl;
print(input->Right);
}
}
void intTree::print() {
print(root);
}
intNode * intTree::rotateRight(intNode *& subTree) {
intNode * newRoot = subTree->Left;
subTree->Left = newRoot->Right;
newRoot->Right = subTree;
setHeight(subTree);
setHeight(newRoot);
return newRoot;
}
intNode * intTree::rotateLeft(intNode *& subTree) {
intNode * newRoot = subTree->Right;
subTree->Right = newRoot->Left;
newRoot->Left = subTree;
setHeight(subTree);
setHeight(newRoot);
return newRoot;
}
intNode* intTree::balanceTree(intNode *& subTree) {
setHeight(subTree);
if (getBalance(subTree) == 2 && getBalance(subTree->Right) < 0) {
cout << "RL" << endl;
subTree->Left = rotateLeft(subTree->Left);
return rotateRight(subTree);
} else if (getBalance(subTree) == 2) { // RR
cout << "RR" << endl;
return rotateRight(subTree);
} else if (getBalance(subTree) == -2 && getBalance(subTree->Left) > 0) { // LR
cout << "LR" << endl;
subTree->Right = rotateRight(subTree->Right);
return rotateLeft(subTree);
} else if (getBalance(subTree) == -2) { // LL
cout << "LL" << endl;
return rotateLeft(subTree);
} else {
return subTree; // balanced
}
}
intTree::intTree() {
root = NULL;
}
void intTree::addNode(int input, intNode *& temp) {
if (temp == NULL) {
temp = new intNode(input);
} else if (input < temp->data) {
cout <<" added to the left" << endl;
addNode(input,temp->Left);
} else if (input > temp->data) {
cout <<" added to the right" << endl;
addNode(input, temp->Right);
}
temp = balanceTree(temp);
}
void intTree::addNode(int input) {
addNode(input, root);
}
void read() {
string num;
int balance, input;
int i = 0;
intTree * intBST = new intTree();
while (i != 10) {
cout << "number?" << endl;
cin >> input;
intNode *tempInt= new intNode(input);
intBST->addNode(input);
i++;
}
cout << "Finished reading in files" << endl;
while (true) {
string userInput;
cin >> userInput;
if (userInput == "Exit") {
cout << "Goodbye!" << endl;
return;
}
if (userInput == "Print") {
intBST->print();
return;
}
}
}
void main() {
read();
return 0;
}
I would appreciate any tips/help on further figuring this out. Let me know if I can provide any more information to help.
Thank you.
I'm new with data structures in C++, and i'm trying to do a doubly linked list with templates. All the examples that i have seen are only for 1 element of the template node, so i'm trying to put 2 elements in the template node in the list, but i don't know how to do it, anyway, i tried to make the list.
Here's the code:
#include<iostream>
#include<cstring>
using namespace std;
template<class T>
// node class
class node
{
public:
node();
node(T);
~node();
node *next;
T data[2];
void borra_todo();
void print();
};
// by defect
template<typename T>
node<T>::node()
{
data[0] = NULL;
data[1] = NULL;
next = NULL;
}
// by parameter
template<typename T>
node<T>::node(T data_)
{
data[0] = data_[0];
data[1] = data_[1];
next = NULL;
}
// delete nodes
template<typename T>
void node<T>::borra_todo()
{
if (next)
next->borra_todo();
delete this;
}
// node printing
template<typename T>
void node<T>::print()
{
cout << data[0] << " " << data[1] << "->";
}
template<typename T>
node<T>::~node() {}
// list
template <class T>
class list
{
private:
node<T> *m_head;
int m_num_nodes;
public:
list();
~list();
void add_head(T);
void add_end(T);
void add_sort(T);
void fill(char r[30], char n[30]);
void search(T);
void del_by_data(T);
void print();
};
template<typename T>
list<T>::list()
{
m_num_nodes = 0;
m_head = NULL;
}
//add in the beginning
template<typename T>
void list<T>::add_head(T data_)
{
node<T> *new_node = new node<T>(data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
new_node->next = m_head;
m_head = new_node;
while (temp)
{
temp = temp->next;
}
}
m_num_nodes++;
}
// add to the last
template<typename T>
void list<T>::add_end(T data_)
{
node<T> *new_node = new node<T> (data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
m_num_nodes++;
}
// it is supposed that sorts items in the list ...
template<typename T>
void list<T>::add_sort(T data_)
{
node<T> *new_node = new node<T> (data_);
node<T> *temp = m_head;
if (!m_head)
{
m_head = new_node;
}
else
{
for (int i =0; i <= 1; i++)
{
if (m_head->data[0] > data_[i])
{
new_node->next = m_head;
m_head = new_node;
}
else
{
while ((temp->next != NULL) && (temp->next->data[0] < data_[i]))
{
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
}
m_num_nodes++;
}
}
// sort adding ...
template<typename T>
void list<T>::fill(char rfc[30])
{
char temprfc[30];
char tempnombre[30];
temprfc = "DUDE010101R0";
tempnombre = "Dude";
add_sort(temprfc, tempnombre);
temprfc = "AUDE010101R1";
tempnombre = "Commander";
add_sort(temprfc, tempnombre);
}
// print list
template<typename T>
void list<T>::print()
{
node<T> *temp = m_head;
if (!m_head)
{
cout << "List is empty" << endl;
}
else
{
while (temp)
{
temp->print();
if (!temp->next)
cout << "NULL\n";
temp = temp->next;
}
}
cout << endl;
}
// search the list
template<typename T>
void list<T>::search(T data_)
{
node<T> *temp=m_head;
int cont=1;
int cont2=0;
while(temp)
{
if(strcmp(temp->data,data_[0]))
{
cout<<"Element found " << temp->data;
cout << " in position: " << cont << endl;
cont2++;
}
temp=temp->next;
cont++;
}
if(cont2==0)
{
cout << "Element not found"<<endl;
}
}
// ... delete by data
template<typename T>
void list<T>::del_by_data(T data_)
{
node<T> *temp = m_head;
node<T> *temp1 = m_head->next;
int cont =0;
if (m_head->data == data_)
{
m_head = temp->next;
}
else
{
while (temp1)
{
if (temp1->data == data_)
{
node<T> *aux_node = temp1;
temp->next = temp1->next;
delete aux_node;
cont++;
m_num_nodes--;
}
temp = temp->next;
temp1 = temp1->next;
}
}
if (cont == 0)
{
cout << "No data" << endl;
}
}
// destroy the constructor
template<typename T>
list<T>::~list() {}
int main()
{
list<char> list1;
char element1[30];
char element2[30];
int dim, choice, pos;
do{
cout << "Select a choice.\n";
cout << "1. Print list\n";
cout << "2. Delete an element of the list\n";
cout << "3. Search an element of the list\n";
cout << "4. Exit\n";
cin >> choice;
switch(choice)
{
case 1:
{
cout << "Printing list:\n";
list1.fill("1","2");
list1.print();
break;
}
case 2:
{
cout << "Element to delete: ";
cin >> element1;
list1.search(element1);
element1 = "";
break;
}
case 3:
{
cout << "Element to search: ";
cin >> element1;
list1.search(element1);
element1 = "";
break;
}
}
}while(choice != 4);
return 0;
}
The code doesn't compile, it marks errors like:
" error: prototype for ‘void list::fill(char*)’ does not match any in class ‘list’
void list::fill(char rfc[30])
^
t3b.cpp:79:8: error: candidate is: void list::fill(char*, char*)
void fill(char r[30], char n[30]);"
Any ideas on how to fix it? Or any ideas on how to put 2 elements in a node using templates?
Thanks in advance.
Dude, you should really try to isolate the error a little bit before posting it. This is 500 lines of code, I had to copy and paste it all into an editor before I could even look at it.
When you declared fill, it had two arguments, when you defined it, it had one. Also, I would avoid arrays of characters for numerous reasons, instead use std::string.
I tested my class member function to add to a linked list outside of my switch and it works. But when I try to use it in my switch, it doesn't. It won't actually add to the list cause when I display the list nothing is there.
Class and implementation:
#ifndef HEADER_H
#define HEADER_H
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
class LinkedList{
template<typename T>
class Node
{
public:
Node(T value = 0) : data(value), nextptr(NULL){};
T retrieve() const{ return data; }
Node<T> *next() const{ return nextptr; }
private:
T data;
Node<T> *nextptr;
friend LinkedList<T>;
};
public:
LinkedList();
LinkedList(const T& x); //Copy Constructor
~LinkedList();
void DisplayList();
void ReverseList();
LinkedList<T> operator= (const LinkedList<T> & x); //Assignment Operator
bool isEmpty() const{ return Size() == 0; }
int Size() const{ return n; }
bool ElementAt(int k, T& x) const;
LinkedList<T>& RemoveAt(int k, T& x)
{
if (k < 0 || k >= Size())
{
cout << "Index not in list.";
}
Node<T> *del = NULL;
if (k == 0)
{
del = list_head;
list_head = del->nextptr;
}
else
{
Node<T> *prev = list_head;
del = list_head->nextptr;
for (int i = 1; i< k; i++)
{
prev = del;
del = del->nextptr;
}
prev->nextptr = del->nextptr;
}
n--; x = del->data; delete del;
return *this;
}
LinkedList<T>& Add(const T& x)
{
Node<T>
*node = new Node<T>(x);
if (Size() == 0)
list_head = node;
else
{
Node<T> *temp = list_head;
while (temp->nextptr)
{
temp = temp->nextptr;
}
temp->nextptr = node;
}
n++;
return *this;
}
private:
Node<T> *list_head;
int n;
};
//Constructor
template<class T>
LinkedList<T>::LinkedList()
{
list_head = NULL;
n = 0;
}
//Copy Constructor
template<class T>
LinkedList<T>::LinkedList(const T& x)
{
list_head = x.listhead;
n = x.n;
}
//Destructor
template<class T>
LinkedList<T>::~LinkedList()
{
Node<T> *temp = list_head, *del, *nextptr;
while (temp != NULL)
{
del = temp->nextptr;
delete temp;
temp = del;
}
}
template<class T>
bool LinkedList<T>::ElementAt(int k, T& x) const
{
if (k < 0 || k >= Size())
return false;
Node<T> *temp = list_head;
for (int i = 0; i< k; i++)
{
temp = temp->next;
}
x = temp->data;
return true;
}
// Assignment Operator
template<class T>
LinkedList<T> LinkedList<T>::operator=(const LinkedList<T> & x)
{
list_head = x.list_head;
n = x.n;
return *this;
}
template<class T>
void LinkedList<T>::DisplayList()
{
Node<T> *temp = list_head;
while (temp != NULL)
{
cout << temp->data << endl;
temp = temp->nextptr;
}
}
template<class T>
void LinkedList<T>::ReverseList()
{
Node<T> *t, *y = list_head, *r = NULL, *listhead;
while (y != NULL)
{
t = y->nextptr;
y->nextptr = r;
r = y;
y = t;
}
list_head = r;
}
#endif
Driver:
#include "stdafx.h"
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
int choice;
string item;
do
{
LinkedList<string> list;
int num;
cout << "1. Add new record to the file" << endl;
cout << "2. Delete a record in the file (by index)" << endl;
cout << "3. Display entire list of items" << endl;
cout << "4. Display entire list of items backwards" << endl;
cout << "5. Exit" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
cout << "1. Add new record to the file" << endl;
cout << "Enter the Item Description:" << endl;
cin.ignore();
getline(cin, item);
list.Add(item);
}
break;
case 2:
{
cout << "2. Delete a record in the file" << endl;
cout << "Enter the index number of the item you want to delete" << endl;
cin >> num;
//list.RemoveAt(num);
}
break;
case 3:
{
cout << "3. Display entire list of items" << endl;
list.DisplayList();
}
break;
case 4:
{
cout << "4. Display entire list of items backwards" << endl;
list.ReverseList();
list.DisplayList();
list.ReverseList();
}
break;
case 5:
{
return 0;
}
break;
}
} while (0 < choice < 6);
return 0;
}
Any ideas?
Move your list declaration outside of your do..while loop. At the moment it is being reinitialized each time round the loop.
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.