I am trying to implement a linked list with an object class. The following is my implementation.
Prof header file:
#ifndef PROF_H
#define PROF_H
#include <iostream>
#include <string>
using namespace std;
class Prof
{
public:
string first_name;
string last_name;
int room_number;
string phone_number;
};
#endif /* PROF_H */
LinkedList header file:
#ifndef LinkedList_h
#define LinkedList_h
#include <iostream>
#include <string>
#include "Prof.h"
using namespace std;
struct Node {
Prof prof;
Node *next;
};
class LinkedList{
private:
Node * head;
int length;
// public members
public:
// Default Constructor
LinkedList();
bool insertProfessor( Node * newNode, int position );
bool removeProfessor( int position );
void printProfessors();
void sortProfessors();
void searchProfessors(string name);
bool insert( Node * newNode);
// Destructor
~LinkedList();
};
#endif
LinkedList class:
#include "LinkedList.h"
#include "Prof.h"
// Default Constructor creates the head node.
LinkedList::LinkedList()
{
head -> prof;
head -> next=NULL;
length = 0;
}
bool LinkedList::insertProfessor( Node * newNode, int position )
{
if ((position <= 0) || (position > length + 1))
{
cout << "Error: No such position\n";
return false;
}
if (head -> next == NULL)
{
head -> next = newNode;
length++;
return true;
}
int count = 0;
Node * p = head;
Node * q = head;
while (q)
{
if (count == position)
{
p -> next = newNode;
newNode -> next = q;
length++;
return true;
}
p = q;
q = p -> next;
count++;
}
if (count == position)
{
p -> next = newNode;
newNode -> next = q;
length++;
return true;
}
cout << "Error: The professor was not added to the list.\n";
return false;
}
void LinkedList::sortProfessors()
{
Node * p = head;
Node * q = head;
Node * k = head;
Node * m = head;
int count = 0;
while(count<length){
while (q)
{
p = q;
k = p -> next;
m = k -> next;
if(p -> prof.first_name > k->prof.first_name){
p->next = m;
k->next = p;
} else if(p -> prof.first_name == k->prof.first_name){
if(p -> prof.last_name > k->prof.last_name){
p->next = m;
k->next = p;
}
}
q = p -> next;
}
count++;
}
}
void LinkedList::searchProfessors(string name){
bool found;
Node * p = head;
Node * q = head;
cout << "Professors";
cout << "\n---------------------------\n";
while (!found)
{
p = q;
if((p->prof.first_name==name) || (p->prof.last_name==name)){
cout << "Found!!\n"<< endl;
cout << "\t" << p -> prof.first_name<<" "<<p -> prof.last_name << endl;
cout << "\tPhone number: " << p -> prof.phone_number << endl;
cout << "\tRoom Number: "<< p -> prof.room_number << endl;
cout << "\n";
found = true;
}
q = p -> next;
}
}
bool LinkedList::removeProfessor( int position )
{
if ((position <= 0) || (position > length + 1))
{
cout << "Error: No such position.\n";
return false;
}
if (head -> next == NULL)
{
cout << "Error: The list is empty.\n";
return false;
}
int count = 0;
Node * p = head;
Node * q = head;
while (q)
{
if (count == position)
{
p -> next = q -> next;
delete q;
length--;
return true;
}
p = q;
q = p -> next;
count++;
}
cout << "nError: No one was removed.\n";
return false;
}
void LinkedList::printProfessors()
{
Node * p = head;
Node * q = head;
cout << "Professors";
cout << "\n---------------------------\n";
while (q)
{
p = q;
cout << "\t" << p -> prof.first_name<<" "<<p -> prof.last_name << endl;
cout << "\tPhone number: " << p -> prof.phone_number << endl;
cout << "\tRoom Number: "<< p -> prof.room_number << endl;
cout << "\n"<<endl;
q = p -> next;
}
}
bool LinkedList::insert( Node * newNode){
while(false){
if (head -> next == NULL)
{
head -> next = newNode;
length++;
return true;
} else {
Node * next = head -> next;
head=next;
false;
}
}
}
LinkedList::~LinkedList()
{
Node * p = head;
Node * q = head;
while (q)
{
p = q;
q = p -> next;
if (q) delete p;
}
}
main file:
#include <cstdlib>
#include <string>
#include <iostream>
#include "LinkedList.h"
#include "Prof.h"
using namespace std;
LinkedList professorsList;
int main()
{
LinkedList professorsList;
int choice=0;
cout<<"Please select your choice.\n 1. Insert.\n 2.Search.\n 3.Delete.\n 4.Exit."<<endl;
cin >> choice;
string keyword="";
int position;
switch(choice){
case 1:
cout<<"Please select you source of input.\n 1.Console.\n 2.File.\n";
cin >> choice;
break;
case 2:
cout<<"Please the name you would like to search.\n";
cin >> keyword;
professorsList.searchProfessors(keyword);
break;
case 3:
cout<<"Please the position of the professor you would like to delete.\n";
cin >> position;
professorsList.removeProfessor(position);
return 0;
break;
case 4:
exit(0);
return 0;
break;
}
return 0;
}
void getInput(int choice){
string first_name;
string last_name;
string phonenumber;
int room_number;
string filename;
Node * professor = new Node;
switch(choice){
case 1:
cout<<"Please enter the professor's first name.\n";
cin >> first_name;
cout<<"Please enter the professor's last name.\n";
cin >> last_name;
cout<<"Please enter the professor's phone number.\n";
cin >> phonenumber;
cout<<"Please enter the professor's room number.\n";
cin >> room_number;
professor->prof.first_name = first_name;
professor->prof.last_name = last_name;
professor->prof.phone_number = phonenumber;
professor->prof.room_number = room_number;
professorsList.insert(professor);
break;
case 2:
cout<< "Enter the file name.\n"<<endl;
cin>>filename;
break;
}
}
When I try to run the program, I get the following error.
RUN FINISHED; Segmentation fault; core dumped; real time: 170ms; user: 0ms; system: 0ms
Please help me solve that error.
Related
When I run my program, everything works as expected until the destructor of the LList class. On the line that says delete current;, I get the following error:
BlankConsoleLab.exe has triggered a breakpoint.
I have been trying to solve this issue for a long time. I would appreciate it if perhaps someone could try to point out what I am doing wrong here.
Below is my code for the program. Thank you
Linked List Class
class LList
{
private:
Node* head;
Node* tail;
int size = 0;
public:
LList()
{
head = nullptr;
tail = nullptr;
size = 0;
}
LList(Node* h, Node* t)
{
this->head = h;
this->tail = t;
}
~LList()
{
Node* current = head;
while (current != nullptr) {
Node* next = current->m_next;
delete current;
current = next;
}
}
void print()
{
//temporary node pointer to traverse through the linked list
Node* temp = head;
cout << endl << "<MY LINKED LIST>\n";
while (temp != nullptr)
{
cout << temp->m_data.firstName << " ";
cout << temp->m_data.lastName << " ";
cout << temp->m_data.hrWage << " ";
cout << temp->m_data.hrWork << " " << endl;
temp = temp->m_next;
}
cout << endl;
}
void removeFirst()
{
//case 1: linked list is empty (never enters loop)
//case 2: linked list is not empty
if (head != nullptr)
{
Node* temp = head;
head = head->m_next;
delete temp;
//decrease size tracker of the linked list
size--;
}
}
void removeLast()
{
//case 1: linked list is empty (never enters loop)
//case 2: linked list has one node
if (head->m_next == nullptr)
{
removeFirst();
}
//case 3: linked list has more than one node
else if (head != nullptr)
{
Node* cur = head;
Node* prev = nullptr;
while (cur->m_next != nullptr)
{
prev = cur;
cur = cur->m_next;
}
tail = prev;
tail->m_next = nullptr;
delete cur;
//decrease size tracker of the linked list
size--;
}
}
//void removeAt(int pos)
//{
// //Case 1: input is invalid (less than 1 or greater than size)
// if (pos < 1 && pos > size)
// {
// return;
// }
// //Case 2: input is position 1
// else if (pos == 1)
// {
// removeFirst();
// }
// //Case 3: input is the last position (input equals size)
// else if (pos == size)
// {
// removeLast();
// }
// //Case 4: input is valid, and not 1 or last position (greater than 1 and less than size)
// else if (head != nullptr)
// {
// Node* cur = head;
// Node* prev = nullptr;
// for (int i = 1; i < pos; i++)
// {
// prev = cur;
// cur = cur->m_next;
// }
// prev->m_next = cur->m_next;
// delete cur;
// size--;
// }
//}
Node* swap(Node* lh, Node* rh)
{
Node* temp = rh->m_next;
rh->m_next = lh;
lh->m_next = temp;
return rh;
}
void readBin()
{
ifstream file;
file.open("C:\\Users\\there\\source\\repos\\cst126-lab9-JEmersonLawrance\\BlankConsoleLab\\Employee Data.bin", ios::binary);
if (file)
{
Node* cur = head;
Node* prev = nullptr;
for (int i = 0; i < 4; i++)
{
file.read((char*)&cur->m_data.firstName, sizeof(cur->m_data.firstName));
file.read((char*)&cur->m_data.lastName, sizeof(cur->m_data.lastName));
file.read((char*)&cur->m_data.hrWage, sizeof(cur->m_data.hrWage));
file.read((char*)&cur->m_data.hrWork, sizeof(cur->m_data.hrWork));
prev = cur;
cur = cur->m_next;
}
return;
}
else
{
cout << "File could not be opened..\n" << endl;
}
file.close();
}
void writeBin()
{
ofstream file;
file.open("Employee Data Output.bin", ios::binary);
if (file)
{
Node* cur = head;
Node* prev = nullptr;
while (cur != nullptr)
{
file.write((char*)&cur->m_data.firstName, sizeof(cur->m_data.firstName));
file.write((char*)&cur->m_data.lastName, sizeof(cur->m_data.lastName));
file.write((char*)&cur->m_data.hrWage, sizeof(cur->m_data.hrWage));
file.write((char*)&cur->m_data.hrWork, sizeof(cur->m_data.hrWork));
prev = cur;
cur = cur->m_next;
}
}
else
{
cout << "File could not be opened..\n" << endl;
}
file.close();
}
};
Node Class
class Node
{
public:
Employee m_data;
Node* m_next;
Node()
{
m_data.firstName = "";
m_data.lastName = "";
m_data.hrWage = 0;
m_data.hrWork = 0;
m_next = nullptr;
}
Node(Node* next)
{
m_data.firstName = "";
m_data.lastName = "";
m_data.hrWage = 0;
m_data.hrWork = 0;
m_next = next;
}
Node(const Node& copy)
{
m_data.firstName = copy.m_data.firstName;
m_data.lastName = copy.m_data.lastName;
m_data.hrWage = copy.m_data.hrWage;
m_data.hrWork = copy.m_data.hrWork;
}
Node operator = (const Node& copy)
{
m_data.firstName = copy.m_data.firstName;
m_data.lastName = copy.m_data.lastName;
m_data.hrWage = copy.m_data.hrWage;
m_data.hrWork = copy.m_data.hrWork;
return *this;
}
~Node()
{
}
};
Employee Class
struct Employee
{
public:
string firstName;
string lastName;
int hrWage;
int hrWork;
Employee()
{
firstName = "";
lastName = "";
hrWage = 0;
hrWork = 0;
}
Employee(string first, string last, int wage, int work)
{
firstName = first;
lastName = last;
hrWage = wage;
hrWork = work;
}
~Employee()
{
}
void getInput()
{
for (int i = 0; i < 4; i++)
{
cout << "EMPLOYEE # " << i+1 << ":\n" << endl;
cout << "First name: ";
cin >> this[i].firstName;
cout << "Last name: ";
cin >> this[i].lastName;
cout << "Hourly Wage: ";
cin >> this[i].hrWage;
cout << "Hours Worked: ";
cin >> this[i].hrWork;
}
}
void writeBin()
{
ofstream file;
file.open("C:\\Users\\there\\source\\repos\\cst126-lab9-JEmersonLawrance\\BlankConsoleLab\\Employee Data.bin", ios::binary);
if (file)
{
for (int i = 0; i < 4; i++)
{
file.write((char*)&this[i].firstName, sizeof(this[i].firstName));
file.write((char*)&this[i].lastName, sizeof(this[i].lastName));
file.write((char*)&this[i].hrWage, sizeof(this[i]).hrWage);
file.write((char*)&this[i].hrWork, sizeof(this[i]).hrWork);
}
}
else
{
cout << "File could not be opened..\n" << endl;
}
file.close();
}
};
Main Function
int main()
{
cout << "In this program, LIST will read the user information"
<< " in from a binary file, and output it into a different binary"
<< " file.\n" << endl;
Employee data[4];
data->getInput();
data->writeBin();
//creating linked list
Node fourth;
Node third(&fourth);
Node second(&third);
Node first(&second);
LList LIST(&first, &fourth);
LIST.readBin();
LIST.writeBin();
LIST.print();
return 0;
}
In main(), you are constructing your LIST object with pointers to local Node objects that are created in automatic memory within main()'s call frame. When main() exits, all of its local variables are destroyed automatically. But, when the LIST object is destroyed, its destructor tries to call delete on those Node objects which were not created in dynamic memory with new. Thus, your code exhibits undefined behavior.
I am trying to make a tree data structure with c++. Originally I tested with int data, it was going fine. However, when I try to use a string data type, it keeps showing an unhandled exception. It said read access violation, this was 0x5D. I don't know what is causing the error. The complete same code only changing int to string causes the violation.
Main:
#include <bits/stdc++.h>
#include "Tree.h"
using namespace std;
int main()
{
Tree A;
int choice; bool isCre=0;
cout << "Input choice : ";
while (cin >> choice) {
switch (choice)
{
case 1:
if (!isCre) {
A.create_tree(); isCre = 1;
break;
}
else {
A.add_tree();
break;
}
case 2:
A.delete_tree(); break;
case 3:
A.modify_tree(); break;
case 4:
A.display_tree(); break;
}
cout << "Input choice : ";
}
}
Header file:
#ifndef TREE_H
#define TREE_H
#include <bits/stdc++.h>
using namespace std;
class Tree
{
private:
struct Tre
{
Tre* parent; Tre* right; Tre* left;
string data;
Tre(Tre* parent, string data)
{
this->parent = parent;
this->data = data;
left = right = NULL;
}
};
Tre* root;
Tre* create(Tre*& root, string data)
{
Tre* p;
p = new Tre(NULL, data);
root = p;
return root;
}
void dis(Tre* node)
{
if (node == NULL)
return;
cout << node->data << endl;
dis(node->left);
dis(node->right);
}
Tre* search(Tre* node, string data)
{
if (node == NULL)
return NULL;
if (node != NULL && node->data == data)
return node;
/* then recur on left subtree */
Tre* p = search(node->left, data);
// node found, no need to look further
if (p != NULL && p->data == data) return p;
/* node is not found in left,
so recur on right subtree */
Tre* q = search(node->right, data);
if (q != NULL && q->data == data) return q;
}
Tre* add(Tre* root, string find, string input)
{
Tre* p = root;
p = search(root, find);
if (p->left != NULL)
{
p->right = new Tre(p, input);
//p->left = new Tre(p, input);
}
else if (p->left == NULL)
{
p->left = new Tre(p, input);
//p->right = new Tre(p, input);
}
return root;
}
Tre* del(Tre* root, string data)
{
Tre* p = root, * q;
p = search(root, data);
q = p->parent;
if (q->right != NULL && q->right->data == data)
{
q->right = NULL;
delete p;
}
else if (q->left->data == data)
{
q->left = NULL;
delete p;
}
return root;
}
Tre* modify(Tre* root, string find, string input)
{
Tre* p = root;
p = search(p, find);
p->data = input;
return root;
}
public:
void create_tree();
void display_tree();
void add_tree();
void delete_tree();
void modify_tree();
};
#endif
#endif
Implementation file:
#include "Tree.h"
void Tree::create_tree()
{
string data;
cout << "Input data : "; cin >> data;
create(root, data);
}
void Tree::display_tree()
{
dis(root);
}
void Tree::add_tree()
{
string find, input;
cout << "Parent data : "; cin >> find;
cout << "New data : "; cin >> input;
add(root, find, input);
}
void Tree::delete_tree()
{
string data;
cout << "Delete data : "; cin >> data;
del(root, data);
}
void Tree::modify_tree()
{
string find, input;
cout << "Find data : "; cin >> find;
cout << "New data : "; cin >> input;
modify(root, find, input);
}
Adding integers to list works fine, but there's something wrong with deleting and printing.
I'm not friendly with debugger yet, but I found out that there is error from node pointer 'first'. Its value is -17891602. I don't know what happened...
#include <iostream>
using namespace std;
class nodeList;
class node {
friend class nodeList;
private:
int data;
node* link;
public:
node() { //constructor
data = 0;
link = NULL;
}
node(int d) { //constructor
data = d;
link = NULL;
}
node(int d, node* l){ //constructor
data = d;
link = l;
}
};
class nodeList {
private:
node* first;
int num = 0;
node* nt;
public:
nodeList() {
first = new node();
}
node* end(node* t){ //return pointer of last element
t = first;
for (int i = 0; i < num; i++){
t = t->link;
}
return t;
}
void add(int a){ //add 'a' at the end of the list
node* x = new node(a);
node* y = this->end(nt);
y->link = x;
num++;
}
void del(int n){ //n : data of element that you want to delete from list
node* temp = first;
node* pretemp = NULL;
node* x;
int i;
for (i = 0; i <= this->num; i++){ //loop to find 'n'
pretemp = temp;
temp = temp->link;
if (n == temp->data){
break;
}
}
temp = first;
for (int j = 0; j<i; j++){ //i : where 'n' is,
temp = temp->link;
}
x = temp->link;
pretemp->link = x;
delete temp;
num--;
}
void printList(){
node* temp = first;
temp = temp->link;
for (int i = 0; i<this->num; i++){
cout << temp->data << endl;
temp = temp->link;
}
}
};
int main(){
nodeList *l = new nodeList();
int a;
int select;
while (1){
cout << "1. ADD 2. DELETE 3. PRINT" << endl;
cin >> select;
if (select == 1){
cout << "Enter an integer: ";
cin >> a;
if (cin.fail()) {
cout << "Wrong input" << endl;
break;
}
l->add(a);
l->printList();
}
if (select == 2){
cout << "Enter the data of the element you want to delete: ";
cin >> a;
if (cin.fail()) {
cout << "Wrong input" << endl;
break;
}
l->del(a);
l->printList();
}
if (select == 3){
l->printList();
}
}
}
Your del function deletes pretemp node (node that was before the one that you need to delete).
Here's possible fix:
//n : data of element that you want to delete from list
void del(int n)
{
//loop to find 'n'
for (node *tmp = first; tmp->link; tmp = tmp->link)
{
if (n == tmp->link->data)
{
node *x = tmp->link;
tmp->link = tmp->link->link;
delete x;
num--;
break;
}
}
}
Also, was your del supposed to delete all nodes with data == n?
These functions are a bit complicated. Here is a simpler idea:
void del(int n){
node* pretemp = first, *temp = first->link;
if(pretemp->data == n) { //handle the deleting of the first node
first = first->link;
delete pretemp;
return;
}
while(temp != NULL && temp->data != n) { //find the node with the data member "n"
pretemp = temp;
temp = temp->link;
}
if(temp != NULL) { //if you found the node, delete it
pretemp->link = temp->link;
delete temp;
}
--num;
}
Your code is a bit over-complicated for what it needs.
Try something more like this instead:
#include <iostream>
#include <limits>
using namespace std;
class nodeList;
class node
{
friend class nodeList;
private:
int data;
node* link;
public:
node(int d = 0) //constructor
: data(d), link(NULL)
{
}
};
class nodeList
{
private:
node* first;
int num;
public:
nodeList()
: first(NULL), num(0)
{
}
~nodeList()
{
node *n = first, *t;
while (n)
{
t = n->link;
delete n;
n = t;
}
}
void add(int data) //add 'data' at the end of the list
{
node* n = new node(data);
if (!first)
first = n;
else
{
node *t = first;
while (t->link)
t = t->link;
t->link = n;
}
++num;
}
void del(int data) //data : data of element that you want to delete from list
{
node* n = first;
node* prev = NULL;
while (n) //loop to find 'data'
{
if (data == n->data)
{
if (prev)
prev->link = n->link;
if (n == first)
first = n->link;
delete n;
--num;
return;
}
prev = n;
n = n->link;
}
}
void printList()
{
for(node* n = first; n != NULL; n = n->link)
cout << n->data << endl;
}
};
int main()
{
nodeList l;
int input;
bool keepGoing = true;
do
{
cout << "1. ADD 2. DELETE 3. PRINT 4. EXIT" << endl;
if (!(cin >> input))
{
cout << "Wrong input" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
}
else
{
switch (input)
{
case 1:
cout << "Enter an integer: ";
if (!(cin >> input))
{
cout << "Wrong input" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
}
else
{
l.add(input);
l.printList();
}
break;
case 2:
cout << "Enter the data of the element you want to delete: ";
if(!(cin >> input))
{
cout << "Wrong input" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
}
else
{
l.del(input);
l.printList();
}
break;
case 3:
l.printList();
break;
case 4:
keepGoing = false;
break;
default:
cout << "Wrong input" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
break;
}
}
}
while (keepGoing);
return 0;
}
If you add an extra node* member to your nodeList class, you can simplify and speed up your add() method:
class nodeList
{
private:
node* first;
node* last;
int num;
public:
nodeList()
: first(NULL), last(NULL), num(0)
{
}
~nodeList()
{
node *n = first, *t;
while (n)
{
t = n->link;
delete n;
n = t;
}
}
void add(int data) //add 'data' at the end of the list
{
node* n = new node(data);
if (!first)
first = n;
if (last)
last->link = n;
last = n;
++num;
}
void del(int data) //data : data of element that you want to delete from list
{
node* n = first;
node* prev = NULL;
while (n) //loop to find 'data'
{
if (data == n->data)
{
if (prev)
prev->link = n->link;
if (n == first)
first = n->link;
if (n == last)
last = prev;
delete n;
--num;
return;
}
prev = n;
n = n->link;
}
}
void printList()
{
for(node* n = first; n != NULL; n = n->link)
cout << n->data << endl;
}
};
And if you can change your list to be a double-linked list instead of a single-linked list, you can simplify your del() method as well:
#include <iostream>
#include <limits>
using namespace std;
class nodeList;
class node
{
friend class nodeList;
private:
int data;
node* prev;
node* next;
public:
node(int d = 0) //constructor
: data(d), prev(NULL), next(NULL)
{
}
};
class nodeList
{
private:
node* first;
node* last;
int num;
public:
nodeList()
: first(NULL), last(NULL), num(0)
{
}
~nodeList()
{
node *n = first, *t;
while (n)
{
t = n->next;
delete n;
n = t;
}
}
void add(int data) //add 'data' at the end of the list
{
node* n = new node(data);
if (!first)
first = n;
if (last)
last->next = n;
n->prev = last;
last = n;
++num;
}
void del(int data) //data : data of element that you want to delete from list
{
for(node* n = first; n != NULL; n = n->next) //loop to find 'data'
{
if (data == n->data)
{
if (n->prev)
n->prev->next = n->next;
if (n->next)
n->next->prev = n->prev;
if (n == first)
first = n->next;
if (n == last)
last = n->prev;
delete n;
--num;
return;
}
}
}
void printList()
{
for(node* n = first; n != NULL; n = n->next)
cout << n->data << endl;
}
};
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 have the following code but it gives an error on the line - e = list.first();(towards the end of the code). It says that it cannot convert Node to char can someone tell me how to get return the first value from the linked list in the variable e.
Thanks for all the help:)
//
// main.cpp
// cprogram1
//
#include <iostream>
using namespace std;
class Node {
char data;
Node* next;
public:
Node() {};
void SetData(int aData) { data = aData; };
void SetNext(Node* aNext) { next = aNext; };
char Data() { return data; };
Node* Next() { return next; };
};
// List class
class List {
Node *head;
public:
List() { head = NULL; };
void Print();
void Append(int data);
void Delete(int data);
Node * First() const;
};
/**
* Print the contents of the list
*/
void List::Print() {
// Temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL ) {
cout << "EMPTY" << endl;
return;
}
// One node in the list
if ( tmp->Next() == NULL ) {
cout << tmp->Data();
cout << " --> ";
cout << "NULL" << endl;
}
else {
// Parse and print the list
do {
cout << tmp->Data();
cout << " --> ";
tmp = tmp->Next();
}
while ( tmp != NULL );
cout << "NULL" << endl;
}
}
/**
* Append a node to the linked list
*/
void List::Append(int data) {
// Create a new node
Node* newNode = new Node();
newNode->SetData(data);
newNode->SetNext(NULL);
// Create a temp pointer
Node *tmp = head;
if ( tmp != NULL ) {
// Nodes already present in the list
// Parse to end of list
while ( tmp->Next() != NULL ) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->SetNext(newNode);
}
else {
// First node in the list
head = newNode;
}
}
/**
* Delete a node from the list
*/
void List::Delete(int data) {
// Create a temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL )
return;
// Last node of the list
if ( tmp->Next() == NULL ) {
delete tmp;
head = NULL;
}
else {
// Parse thru the nodes
Node *prev;
do {
if ( tmp->Data() == data ) break;
prev = tmp;
tmp = tmp->Next();
} while ( tmp != NULL );
// Adjust the pointers
prev->SetNext(tmp->Next());
// Delete the current node
delete tmp;
}
}
Node * List::First() const {
Node *tmp = head;
return head;
}
int main ()
{
char c;
int t = 0;
char e;
List list;
while(t==0)
{
cout << "Please enter your command";
cin >> c;
if(c=='c')
{
cout << "You will need to enter 6 letters, one after the other";
cout << "Please enter the first letter";
cin >> e;
list.Append(e);
cout << "Please enter the second letter";
cin >> e;
list.Append(e);
cout << "Please enter the third letter";
cin >> e;
list.Append(e);
cout << "Please enter the fourth letter";
cin >> e;
list.Append(e);
cout << "Please enter the fifth letter";
cin >> e;
list.Append(e);
cout << "Please enter the sixth letter";
cin >> e;
list.Append(e);
list.Print();
list.Delete('b');
list.Print();
e = list.First();
}
}
}
Lets take a look to your program : tested here :
#include <iostream>
using namespace std;
class Node {
char data;
Node* next;
public:
Node() {};
void SetData(int aData) { data = aData; };
void SetNext(Node* aNext) { next = aNext; };
char Data() { return data; };
Node* Next() { return next; };
};
// List class
class List {
Node *head;
public:
List() { head = NULL; };
void Print();
void Append(int data);
void Delete(int data);
Node * First() const;
};
/**
* Print the contents of the list
*/
void List::Print() {
// Temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL ) {
cout << "EMPTY" << endl;
return;
}
// One node in the list
if ( tmp->Next() == NULL ) {
cout << tmp->Data();
cout << " --> ";
cout << "NULL" << endl;
}
else {
// Parse and print the list
do {
cout << tmp->Data();
cout << " --> ";
tmp = tmp->Next();
}
while ( tmp != NULL );
cout << "NULL" << endl;
}
}
/**
* Append a node to the linked list
*/
void List::Append(int data) {
// Create a new node
Node* newNode = new Node();
newNode->SetData(data);
newNode->SetNext(NULL);
// Create a temp pointer
Node *tmp = head;
if ( tmp != NULL ) {
// Nodes already present in the list
// Parse to end of list
while ( tmp->Next() != NULL ) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->SetNext(newNode);
}
else {
// First node in the list
head = newNode;
}
}
/**
* Delete a node from the list
*/
void List::Delete(int data) {
// Create a temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL )
return;
// Last node of the list
if ( tmp->Next() == NULL ) {
delete tmp;
head = NULL;
}
else {
// Parse thru the nodes
Node *prev;
do {
if ( tmp->Data() == data ) break;
prev = tmp;
tmp = tmp->Next();
} while ( tmp != NULL );
// Adjust the pointers
prev->SetNext(tmp->Next());
// Delete the current node
delete tmp;
}
}
Node * List::First() const {
Node *tmp = head;
return head;
}
int main ()
{
char c;
int t = 0;
char e;
List list;
while(t==0)
{
cout << "Please enter your command";
c = 'c';
//cin >> c;
if(c=='c')
{
cout << "You will need to enter 6 letters, one after the other";
cout << "Please enter the first letter";
list.Append('e');
cout << "Please enter the second letter";
//cin >> e;
list.Append('a');
cout << "Please enter the third letter";
//cin >> e;
list.Append('b');
cout << "Please enter the fourth letter";
//cin >> e;
list.Append('f');
cout << "Please enter the fifth letter";
//cin >> e;
list.Append('h');
cout << "Please enter the sixth letter";
//cin >> e;
list.Append(e);
list.Print();
list.Delete('b');
list.Print();
e = list.First()->Data();
t=1;
}
}
}
As you can see, e = list.First() return a pointer to a Node, not a char. You have implemented a function that return a char which is Data(). Thus, you should use e = list.First()->Data();.
Also, your loop is infinite because t is always 0. I just put t=1 to stop your loop and see the result. (if you use this code, don't forget to uncomment the cin and remove c = 'c')
Hope that helps you.
When I run your code I get the error:
main.cpp: error: assigning to 'char' from incompatible type 'Node *'
e = list.First();
^ ~~~~~~~~~~~~
which I think explains it.
Try this:
e = list.First()->Data();