I've been having some trouble getting my program to insert given names along with their weights in a linked list which has a respective link for names and weights, which are both to be sorted in ascending / alphabetical order. The weight links work fine but I can't seem to identify what I'm getting wrong in my name linker. Any help would be greatly appreciated. The problem most likely lies in the insertName() private function.
#include <iostream>
#include <string>
using namespace std;
class DoublyLinkedList
{
public:
void insert(string name, double weight);
void printNameAsc();
void printWeightAsc();
private:
struct Node
{
string name;
double weight;
Node* nextName;
Node* nextWeight;
};
Node* nameHead = NULL;
Node* weightHead = NULL;
Node* newP = NULL;
void insertName();
void insertWeight();
};
void DoublyLinkedList::insert(string name, double weight)
{
// variable declaration
newP = new Node;
newP->name = name;
newP->weight = weight;
newP->nextName = NULL;
newP->nextWeight = NULL;
// empty first element check
if (nameHead == NULL && weightHead == NULL)
{
nameHead = newP;
weightHead = newP;
return;
}
// name and weight insertion
insertName();
insertWeight();
return;
}
void DoublyLinkedList::insertName()
{
Node* activeP = nameHead;
Node* prevP = NULL;
// traversing through name links
while (true)
{
if (activeP == NULL)
{
break;
}
if ((activeP->name).compare(newP->name))
{
break;
}
prevP = activeP;
activeP = activeP->nextName;
}
//insertion
newP->nextName = activeP;
if (activeP == nameHead)
{
nameHead = newP;
}
else
{
prevP->nextName = newP;
}
return;
}
void DoublyLinkedList::insertWeight()
{
Node* activeP = weightHead;
Node* prevP = NULL;
// traversing through weight links
while (true)
{
if (activeP == NULL)
{
break;
}
if (newP->weight < activeP->weight)
{
break;
}
prevP = activeP;
activeP = activeP->nextWeight;
}
//insertion
newP->nextWeight = activeP;
if (activeP == weightHead)
{
weightHead = newP;
}
else
{
prevP->nextWeight = newP;
}
return;
}
void DoublyLinkedList::printNameAsc()
{
Node* activeP = nameHead;
while (activeP != NULL)
{
cout << activeP->name << " " << activeP->weight << endl;
activeP = activeP->nextName;
}
return;
}
void DoublyLinkedList::printWeightAsc()
{
Node* activeP = weightHead;
while (activeP != NULL)
{
cout << activeP->name << " " << activeP->weight << endl;
activeP = activeP->nextWeight;
}
return;
}
int main()
{
DoublyLinkedList nameList;
nameList.insert("Michael", 275);
nameList.insert("Tom", 150);
nameList.insert("Abe", 200);
nameList.printNameAsc();
system("pause");
nameList.printWeightAsc();
system("pause");
return 0;
}
Pretty sure your problem is here:
if ((activeP->name).compare(newP->name) > 0)
{
break;
}
Looks like you're finding the insertion point with activeP. When activeP->name > newP->name, you want to stop searching.
if ((activeP->name).compare(newP->name))
Is invalid, this will evaluate true if activeP < newP (compare statement is -1) or activeP > newP (compare statement is 1), effectively only skipping people with the same names.
Remember, carried over from C, truth is defined as not falseness, which is defined as (!0)
Also, why not just pass a reference of newP to insertName() and insertWeight()? It's good practice to not leave (possibly dangling) pointers stored as member variables.
Related
Please provide the implementation of functions append, printList, and delete_evens as described in the comments. You will be dealing with a linked list of pages in which every node (page), is linked to its next and previous node (page) using next and prev pointers respectively. Please note the previous node of the first node (head) is NULL. In a similar way, the next of the last node will also be NULL.
The expected output is as follows:
Created PageList:
(page1)->(page2)->(page3)->(page4)->(page5)->(page6)->(page7)->(page8)->(page9)->(page10)->(page11)->(page12)->(page13)->(page14)->(page15)->(page16)->(page17)->(page18)->(page19)->(page20)->(page21)->(page22)->(page23)->(page24)->(page25)->(page26)->(page27)->(page28)->(page29)->(page30)->(page31)->(page32)->(page33)->(page34)->(page35)->(page36)->(page37)->(page38)->(page39)->(page40)->(page41)->(page42)->(page43)->(page44)->(page45)->(page46)->(page47)->(page48)->(page49)->(page50)->
Updated PageList:
(page1)->(page3)->(page5)->(page7)->(page9)->(page11)->(page13)->(page15)->(page17)->(page19)->(page21)->(page23)->(page25)->(page27)->(page29)->(page31)->(page33)->(page35)->(page37)->(page39)->(page41)->(page43)->(page45)->(page47)->(page49)->
The output I am getting is:
Created PageList:
(page)->1 (page)->2 (page)->3 (page)->4 (page)->5 (page)->6 (page)->7 (page)->8 (page)->9 (page)->10 (page)->11 (page)->12 (page)->13 (page)->14 (page)->15 (page)->16 (page)->17 (page)->18 (page)->19 (page)->20 (page)->21 (page)->22 (page)->23 (page)->24 (page)->25 (page)->26 (page)->27 (page)->28 (page)->29 (page)->30 (page)->31 (page)->32 (page)->33 (page)->34 (page)->35 (page)->36 (page)->37 (page)->38 (page)->39 (page)->40 (page)->41 (page)->42 (page)->43 (page)->44 (page)->45 (page)->46 (page)->47 (page)->48 (page)->49 (page)->50
Updated PageList:
(page)->1 (page)->3 (page)->5 (page)->7 (page)->9 (page)->11 (page)->13 (page)->15 (page)->17 (page)->19 (page)->21 (page)->23 (page)->25 (page)->27 (page)->29 (page)->31 (page)->33 (page)->35 (page)->37 (page)->39 (page)->41 (page)->43 (page)->45 (page)->47 (page)->49
My code is as follows:
#include <iostream>
#include <string>
using namespace std;
class Page {
public:
int page_number = 0;
string page_content = "";
Page *next = NULL;
Page *prev = NULL; // previous
};
class PageList {
public:
Page *head = NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content) {
Page *first;
first = new Page();
first->page_content = page_content;
first->next = NULL;
first->prev = NULL;
first->page_number = page_number;
if (head == NULL) {
head = first;
} else {
Page *second = head;
while (second->next != NULL) {
second = second->next;
}
second->next = first;
}
}
// print all the elements of the list (pages) with the given format
void print list(Page *node, bool forward) {
while (node != NULL) {
cout << node->page_content << " ";
node = node->next;
}
cout << endl;
}
void delete_evens() { // delete the pages with even page_number
Page *first = head;
Page *q = NULL;
while (first != NULL) {
if (first->page_number % 2 == 0) {
if (q == NULL) {
head = first->next;
first = first->next;
} else {
q->next = first->next;
first->next = NULL;
first = q->next;
}
} else {
if (q == NULL) {
q = first;
first = first->next;
} else {
q = q->next;
first = first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i = 1; i <= pages; i++) {
append(i, "(page" + to_string(i));
}
cout << "Created PageList:" << endl;
printList(head, true);
delete_evens();
cout << "Updated PageList:" << endl;
printList(head, true);
}
};
int main() {
PageList list(50);
return 0;
}
I believe that the error is somewhere in the line append(i, "(page" + to_string(i));
Can someone please help?
#include <iostream>
#include <string>
using namespace std;
// -------------------------------------------------------------------
class Page {
public:
int page_number = 0;
string page_content = "";
Page* next = NULL;
Page* prev = NULL;// previous
};
class PageList {
public:
Page* head=NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content){
Page* first;
first=new Page();
first->page_content = page_content;
first->next=NULL;
first->prev=NULL;
first->page_number=page_number;
if(head==NULL) {
head=first;
}
else{
Page* second=head;
while(second->next != NULL) {
second=second->next;
}
second->next=first;
}
}
// print all the elements of the list (pages) with the given format
void printList(Page* node, bool forward) {
while(node != NULL) {
cout<<node->page_content<<""<<")->";;
node=node->next;
}
cout<<endl;
}
void delete_evens() // delete the pages with even page_number
{
Page* first = head;
Page* q=NULL;
while(first != NULL)
{
if(first->page_number % 2 == 0)
{
if(q==NULL)
{
head=first->next;
first=first->next;
}
else
{
q->next=first->next;
first->next=NULL;
first=q->next;
}
}
else
{
if(q==NULL)
{
q=first;
first=first->next;
}
else
{
q=q->next;
first=first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i=1;i<=pages;i++){
append(i, "(page" + to_string(i));
}
cout<< "Created PageList:" << endl;
printList(head,true);
delete_evens();
cout<< "Updated PageList:" << endl;
printList(head,true);
}
};
// -------------------------------------------------------------------
int main()
{
PageList list(50);
return 0;
}
I have got a problem in the sorting method of my linked list. I need to sort nodes in a doubly linked list by transferring links of nodes (entries of nodes). The method is stopped due to nullptr in the last node.
I do not know how to solve this problem. I tried a lot of variants, but no one was successful.
#include "DlinkedList.h"
// Node constructor
Node::Node()
{
this->rhetorician = NULL;
this->prev = NULL;
this->next = NULL;
}
// Node destructor
Node::~Node()
{
}
// List constructor
DlinkedList::DlinkedList()
{
this->length = 0;
this->head = NULL;
}
// Method for adding node at the end
void DlinkedList::appendNode(Rhetorician* rhetorician)
{
if (this->head == NULL) {
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
this->head = new_node;
}
else {
Node *last_node = NULL;
for (Node *node_ptr = this->head; node_ptr != NULL; node_ptr = node_ptr->next)
{
last_node = node_ptr;
}
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
last_node->next = new_node;
new_node->prev = last_node;
}
this->length++;
}
// Method for printing nodes
void DlinkedList::printNodes()
{
for (Node *node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
node_cur->rhetorician->printer();
cout << "---------------------------------------------------------------------------------------------------" << endl;
}
cout << endl << "##################################################################################################\n" << endl;
}
// Method for getting length
int DlinkedList::getLenght()
{
return this->length;
}
// Method for deleting node
void DlinkedList::remove(string name)
{
Node* logout_node = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
logout_node = node_cur;
}
}
if (this->head != NULL || logout_node != NULL)
{
if (this->head == logout_node)
{
this->head = logout_node->next;
}
if (logout_node->next != NULL)
{
logout_node->next->prev = logout_node->prev;
}
if (logout_node->prev != NULL)
{
logout_node->prev->next = logout_node->next;
}
delete logout_node->rhetorician;
delete logout_node;
this->length--;
}
}
// Method for finding node
void DlinkedList::find(string name)
{
bool ver = false;
Node *n = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
ver = true;
n = node_cur;
}
}
if (ver)
{
n->rhetorician->printer();
}
else
{
cout << "Rhetorician was not found!";
}
}
// Method for sorting nodes
void DlinkedList::sort()
{
int count = this->getLenght();
Node *tmp, *current;
int i, j;
for (i = 1; i < count; i++)
{
current = this->head;
for (j = 0; j <= count - i - 1; j++)
{
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient)
{
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
current->next = after->next;
current->prev = after;
after->next = current;
after->prev = before;
}
tmp = current;
current = current->next;
}
}
}
// List destructor
DlinkedList::~DlinkedList()
{
Node *next_node = NULL;
for (Node *node_cur = this->head; node_cur != NULL; node_cur = next_node)
{
next_node = node_cur->next;
delete node_cur->rhetorician;
delete node_cur;
}
this->head = NULL;
this->length = 0;
}
Main:
#include <iostream>
#include "DlinkedList.h"
#include <fstream>
#include <vector>
#include <sstream>
// Namespace
using namespace std;
// Parser of line to vector array
vector<string> split(string strToSplit, char delimeter)
{
stringstream ss(strToSplit);
string item;
vector<string> splittedStrings;
while (getline(ss, item, delimeter))
{
splittedStrings.push_back(item);
}
return splittedStrings;
}
// File loader
void read_file(const char *name, DlinkedList *list)
{
// Variable for loading line
string line;
{
// Create relation
ifstream file(name);
// Check if file exists
if (file)
{
// Check if file is empty
if (!(file.peek() == ifstream::traits_type::eof()))
{
// Read data from file and put into LinkedList
while (getline(file, line)) {
list->appendNode(new Rhetorician(split(line, ';')[0], split(line, ';')[1],
split(line, ';')[2], stoi(split(line, ';')[3])));
}
}
// Close file
file.close();
}
}
}
// Main method
int main()
{
// Create instance of doubly linked list
DlinkedList *list = new DlinkedList();
// Read file and push data into list
read_file("seznam_enumat.txt", list);
// Print all loaded rhetoricians behind added own one
cout << "\nAll rhetoricians from file:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Append other rhetoricians
list->appendNode(new Rhetorician("Cain", "Foster", "Structural and molecular virology", 7));
list->appendNode(new Rhetorician("Stacy", "Algar", "Dept of microbiology and immunology", 5));
list->appendNode(new Rhetorician("Oded", "Philander", "Experimental plasma physics", 3));
list->appendNode(new Rhetorician("Shay", "Rimon", "Experimental plasma physics", 10));
// Sort rhetoricians in list
list->sort();
// Delete rhetorician by name
//list->remove("Stacy");
// Finder of rhetorician
cout << "\nFound rhetorician:" << endl;
cout << "##################################################################################################\n" << endl;
list->find("Shay");
// Print all sorted rhetoricians
cout << "\nAll rhetoricians:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Destruct list
delete list;
// Check if user click any key
getchar();
return 0;
}
Rhetorician:
#include "Rhetorician.h"
Rhetorician::Rhetorician(string name, string surname, string contribution, int coefficient)
{
this->name = name;
this->surname = surname;
this->contribution = contribution;
this->coefficient = coefficient;
}
void Rhetorician::printer()
{
// Name
cout << "Name:" << endl;
cout << this->name << endl;
// Surname
cout << "Surname:" << endl;
cout << this->surname << endl;
// Contribution
cout << "Contribution:" << endl;
cout << this->contribution << endl;
// Coefficient
cout << "Coefficient:" << endl;
cout << this->coefficient << endl;
}
The main issue is in sort(). It is not handling the pointers correctly.
Take a short example, 3 -> 2 -> 1 and you will get it.
Here is the corrected code with unnecessary variables removed:
void DlinkedList::sort() {
int count = this->getLenght();
Node *current;
int i, j;
for (i = 1; i < count; i++) {
current = this->head;
for (j = 0; j <= count - i - 1; j++) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
before = current->prev;
after = current->next;
if (before != nullptr) {
before->next = after;
} else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != nullptr) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
} else {
current = current->next; // Go to next node only if current->rhetorician->coefficient > current->next->rhetorician->coefficient condition is false.
}
}
}
}
The upwardly sorted list is working super but when I tried to sort the list downwardly only change the character > for < it is not working. Must be changed before node and after node?
// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}
I have no idea how to delete in a circular link list. For example the head was B, so the list will go from "B, C, D, E, A". The first node will always pick a number from 1-5 which I keep reducing using the counter, so for example if "B" picked 3, the count will start unto it's next node which is "C" so counting from "C", we will have to eliminate "E", once "E" was eliminated.
The new head aka the picker will start unto the next node after the eliminated node, so the next set of nodes will become "A,B,C,D", this function must repeat until there is only 1 last standing node.
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *t, *head;
node *ex;
int paper;
int ctr = 5;
int num;
void create(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL)
{
head = n;
t = n;
}
else
{
t->next = n; // connects the nodes
t = t->next; // moves the connecter to the t= last
}
t->next = head;
}
/*
* Deletion of element from the list
*/
void delete_element(string value)
{
}
//Display Circular Link List
void display()
{
node *temp = new node;
temp = head;
if ((head == NULL) && (t == NULL))
{
}
for (int j = 1; j <= 5; j++)
{
cout << temp->name << "\n";
temp = temp->next;
}
}
void firstpic()
{
srand(time(NULL));
paper = rand() % 5 + 1;
int fctr = 5;
bool p1 = 0, p2 = 0, p3 = 0, p4 = 0, p5 = 0;
if (paper == 1)
{
create("A");//1
fctr--;
}
else if (paper == 2)
{
create("B");//2
p2 = 1;
}
else if (paper == 3)
{
create("C");//2
p3 = 1;
}
else if (paper == 4)
{
create("D");//2
p4 = 1;
}
else if (paper == 5)
{
create("E");//2
p5 = 1;
}
if (p1)
{
create("B");
create("C");
create("D");
create("E");
}
else if (p2)
{
create("C");
create("D");
create("E");
create("A");
}
else if (p3)
{
create("D");
create("E");
create("A");
create("B");
}
else if (p4)
{
create("E");
create("A");
create("B");
create("D");
}
else if (p5)
{
create("A");
create("B");
create("C");
create("D");
}
}
void drawn()
{
node *holder = head;
ex = holder->next;
cout << holder->name << " has drawn: " <<num <<endl;
}
int main()
{
head == NULL;
t == NULL;
srand(time(NULL));
firstpic();
display();
num = rand() % ctr + 1;
drawn();
system("pause>nul");
return 0;
}
Here is something that may suit your needs:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *tail, *head;
void addNode(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL) {
head = n;
tail = n;
} else {
tail->next = n; // connects the nodes
tail = tail->next; // moves the connecter to the t= last
}
tail->next = head;
}
/*
* Deletion of element from the list
*/
void removeNode(string value)
{
// no elements
if (head == NULL) {
return;
}
node *n = head;
node *prev = tail;
// 1 element
if(n == prev) {
if(n->name == value) {
delete n;
head = tail = NULL;
}
return;
}
bool found = false;
// search
do {
if(n->name == value) {
found = true;
break;
}
prev = n;
n = n->next;
} while (n != head);
// no such element
if(!found) {
return;
}
prev->next = n->next;
if(n == head) {
head = n->next;
} else if(n == tail) {
tail = prev;
}
delete n;
}
void displayList()
{
if (head == NULL) {
cout << "empty!" << endl;
return;
}
node *n = head;
do {
cout << n->name << "\n";
n = n->next;
} while (n != head);
cout << endl;
}
void createList()
{
const int count = 5;
std::string names[count] = {"A", "B", "C", "D", "E"};
int nameIndex = rand() % count;
for(int i = 0; i<count; ++i) {
nameIndex += 1;
nameIndex %= count;
addNode(names[nameIndex]);
}
}
int main()
{
srand(time(NULL));
head = NULL;
tail = NULL;
createList();
displayList();
removeNode("A");
displayList();
removeNode("A");
displayList();
removeNode("E");
displayList();
removeNode("B");
displayList();
removeNode("C");
displayList();
removeNode("D");
displayList();
system("pause>nul");
return 0;
}
Note that during node deletion you should take care of such cases as:
No elements case
Last 1 element to be deleted
Head deletion
Tail deletion
Also, never do things like you did in your firstpic() function: it is a painfull way to do it. drawn() function seems not to do anything that makes sence, but it is out of question's scope.
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;
}
Can anybody tell me why my main program is printing out 9460301 instead of 350?
I'm just trying to insert a struct as a single item into a linked list. The struct has atrributes x and y. I then wish to print out the x attribute of the struct in my linked list. I have a huge program written out, and I tried stripping it down on this post just to what's neccessary to view for this new issue that has arisen for me.
My chunk struct and Linkedlist class are as follows:
struct chunk{
int x;
int y;
};
template <class T>
class linkedList
{
public:
class node
{
public:
///node class attributes
T mPayload;
node* mNext;
///constructor
node(T toucan):mPayload(toucan),mNext(NULL)
{}
///destructor
~node()
{
///cascading delete
if(mNext)
delete mNext;
}
///node class methods
};
///linkedList class attributes
node* mStart;
///constructor
linkedList():mStart(NULL)
{}
///destructor
~linkedList()
{
///initializes the cascading delete.
if(mStart)
delete mStart;
}
///linkedList class methods
T mReturnT(int indx)
{
if(!mStart)
{
T emptyList;
return emptyList;
}
else
{
node* cur;
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
}
}
void mInsertHelper(node* blah, T data)
{
if(blah->mNext != NULL)
mInsertHelper(blah->mNext, data);
else
{
blah->mNext = new node(data);
blah->mNext->mNext = NULL;
}
}
void mInsert(T data)
{
if(mStart == NULL)
{
mStart = new node(data);
//mStart->mPayload = data;
}
else
mInsertHelper(mStart, data);
}
T mPop()
{
///Removes the last item in the list,
///and returns it.
if(!mStart)
return NULL;
else
{
node* cur = mStart;
while(cur->mNext)
{
cur = cur->mNext;
}
T var = cur->mPayload;
delete cur;
return var;
}
}
int mSize()
{
if(!mStart)
return 0;
else
{
node* cur = mStart;
int counter = 1;
while(cur->mNext)
{
cur = cur->mNext;
counter++;
}
delete cur;
return counter;
}
}
};
And my main.cpp:
int main()
{
chunk head;
head.x = 350;
head.y = 600;
linkedList<chunk> p1Snake;
p1Snake.mInsert(head);
cout<<p1Snake.mReturnT(0).x<<endl;
}
You never initialise cur before iterating through it.
node* cur; // <-- UNINITIALISED!
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
That first line should be:
node* cur = mStart;
And I think you should use indx instead of indx+1 in that loop... Unless you were using a dummy-head scheme, which you're not.
The logic inside the loop for detecting out-of-bounds is a bit wrong, also. How about revamping the whole thing:
node* cur = mStart;
while( cur && indx > 0 ) {
cur = cur->mNext;
indx--;
}
if( !cur ) {
cout << "Indx out of range." << endl;
return T();
}
return cur->mPayload;