I am trying to create a function that will insert a node to the back of the list using linked list. I am new to using linked list and I have tried many different ways of doing an insertion at the end of the list but nothing seems to be working. The main passes the values one at a time to be inserted 2 4 5 8 9, and the output is 2 0 0 0 0. I do not whats causing this problem.
.h
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext){}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
~Node(){}
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
~AnyList();
//destructor
int getNumOfItems();
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
int count; //keeps track of number of nodes in the list
};
.cpp
void AnyList::insertBack(int b)
{
Node *temp = new Node;
if (ptrToFirst == NULL)
{
temp->setData(b);
ptrToFirst = temp;
}
else
{
Node *first = ptrToFirst;
while (first->getPtrToNext() != NULL)
{
first = first->getPtrToNext();
}
first->setPtrToNext(temp);
}
}
First, you really should be using the std::list or std::forward_list class instead of implementing the node handling manually:
#include <list>
class AnyList
{
public:
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
std::list<int> nodes; //nodes in the list
};
void AnyList::print() const
{
for (std::list<int>::const_iterator iter = nodes.begin(); iter != nodes.end(); ++iter)
{
int value = *iter;
// print value as needed...
}
}
void AnyList::destroyList()
{
nodes.clear();
}
void AnyList::getNumOfItems() const
{
return nodes.size();
}
void AnyList::insertBack(int b)
{
nodes.push_back(b);
}
void AnyList::deleteFirstNode()
{
if (!nodes.empty())
nodes.pop_front();
}
That being said, your manual implementation fails because you are likely not managing the nodes correctly (but you did not show everything you are doing). It should look something like this:
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext) {}
~Node() {}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
~AnyList();
//destructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
Node *ptrToLast; //pointer to point to the last node in the list
int count; //keeps track of number of nodes in the list
};
AnyList:AnyList()
: ptrToFirst(NULL), ptrToLast(NULL), count(0)
{
}
void AnyList::print() const
{
for (Node *temp = ptrToFirst; temp != NULL; temp = temp->getPtrToNext())
{
int value = temp->getData();
// print value as needed...
}
}
AnyList::~AnyList()
{
destroyList();
}
void AnyList::destroyList()
{
Node *temp = ptrToFirst;
ptrToFirst = ptrToLast = NULL;
count = 0;
while (temp != NULL)
{
Node *next = temp->getPtrToNext();
delete temp;
temp = next;
}
}
int AnyList::getNumOfItems() const
{
return count;
}
void AnyList::insertBack(int b)
{
Node *temp = new Node(b, NULL);
if (ptrToFirst == NULL)
ptrToFirst = temp;
if (ptrToLast != NULL)
ptrToLast->setPtrToNext(temp);
ptrToLast = temp;
++count;
}
void AnyList::deleteFirstNode()
{
if (ptrToFirst == NULL)
return;
Node *temp = ptrToFirst;
ptrToFirst = temp->getPtrToNext();
if (ptrToLast == temp)
ptrToLast = NULL;
delete temp;
--count;
}
Related
struct node {
int data{};
node *right{nullptr};
node *left{nullptr};
};
class BTree {
private:
node *root;
void insert(node *sr, int num);
public:
BTree();
void buildTree(int num);
};
void BTree::insert(node *sr, int num) {
if (sr == nullptr) {
sr = new node;
sr->data = num;
} else {
if (num < sr->data)
insert(sr->left, num);
else
insert(sr->right, num);
}
}
int main() {
BTree tree;
tree.buildTree(3);
return 0;
}
I am using the above insert method to add a node to Binary Search Tree. But this method is unable to add the node , if i add a number as its root or first node the root remains nullptr.
How do i resolve this issue.
At the first root is nullptr , and I am sending root i.e the nullptr as the argument. As nullptr does refer to any node therefor the root is not getting updated by the operation in the method.
possible solution:
use pointer to pointer, so that address of the node can be passed and and changed.
directly acces the root to do changes.
PROTOTYPE
void insert(node **sr, int num);
BUILD TREE METHOD
void BTree::buildTree(int num) {
insert(&root, num);
}
INSERT METHOD
void BTree::insert(node **sr, int num) {
if (*sr == nullptr) {
*sr = new node;
(*sr)->data = num;
} else {
if (num < (*sr)->data)
insert(&((*sr)->left), num);
else
insert(&((*sr)->right), num);
}
}
This is the part of code where I want the createNode function to return the node that it creates.
struct Node *ptr = createNode(key);
if(key<prev->data)
{
prev->left = ptr;
}
else
{
prev->right = ptr;
}
createNode Function :-
Node * tree :: createNode(int key). //Unknown type name 'Node'
{
Node * n = new Node;
n->data = key;
n->left = NULL;
n->right = NULL;
return n;
}
declaration of function in class:-
Node * createNode(int key);
structure of Node :-
struct Node
{
int data;
Node *left;
Node *right;
};
when I define the function createNode i'am getting the error that -> Unknown type name 'Node'
how can I define the function whose return type is pointer.
#include <iostream>
#include<stdlib.h>
using namespace std;
class tree
{
struct Node
{
int data;
Node *left;
Node *right;
};
public:
Node * toDelete(Node *root, int key);
void insert(Node *root,int key);
Node * createNode(int key);
int isBST(Node* root);
void preorder(Node *root);
void postorder(Node *root);
void inorder(Node *root);
Node * search(Node *root,int key);
Node * searchIter(Node *root,int key);
Node * findmin(Node *root);
};
void tree :: preorder(Node *root)
{
if(root != NULL)
{
cout<<root->data<<"\t";
preorder(root->left);
preorder(root->right);
}
}
void tree :: postorder(Node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<"t";
}
}
void tree :: inorder(Node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
}
void tree :: insert(Node *root,int key)
{
struct Node *prev = NULL;
while(root!=NULL)
{
prev = root;
if(key<root->data)
{
root = root->left;
}
else
{
root = root->right;
}
}
struct Node *ptr = createNode(key);
if(key<prev->data)
{
prev->left = ptr;
}
else
{
prev->right = ptr;
}
}
Node * tree :: createNode(int key) //Unknown type name 'Node'
{
Node * n = new Node;
n->data = key;
n->left = NULL;
n->right = NULL;
return n; //Cannot initialize return object of type 'int *' with an lvalue of type 'tree::Node *'
}
int main()
{
}
Keep Node outside tree class.
struct Node
{
int data;
Node* left;
Node* right;
};
class tree
{
....
Node is private to your tree class. Hence, it is not directly accessible outside the class the way you are trying in your code.
In one of my classes at Uni we are creating Binary search trees and inserting data and looking them up. My code make sense in my head and because of this I cannot find the error anywhere. I have spent ages trying to find the error but cannot find it anywhere. The only thing that might be causing an error is that the precompiled headers didn't work when I started so i removed them from my project. The error only occurrs when i try to use the BST.Lookup and choose a key that is on the right subtree.
This is my main cpp file:
// BinarySearchTrees.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "BST.h"
#include <iostream>
#include <fstream>
#include <string>
void ReadFile(BST &Bst)
{
int iKey;
std::string Key;
std::string Data;
std::ifstream testFile("Test.txt");
if (testFile.is_open())
{
while (!testFile.eof())
{
getline(testFile, Key, ' ');
getline(testFile, Data);
iKey = stoi(Key);
Bst.Insert(iKey, Data);
}
}
}
int main()
{
std::string Option;
int Choice;
BST BST;
//ReadFile(BST);
BST.Insert(6, "Oscar");
BST.Insert(20, "Ben");
BST.Insert(99, "James");
BST.Insert(1, "Alex");
while (Option != "exit")
{
std::cout << "If you wish to Lookup a Node, Insert value to find. Enter 'exit' to close" << std::endl;
getline(std::cin, Option);
if (Option == "exit")
break;
else
{
Choice = stoi(Option);
BST.Lookup(Choice);
}
}
return 0;
}
I believe that the readfile code may be incorrect but am unsure.
My Binary Search Tree Class:
#include "BST.h"
struct BST::Node {
Key key;
Item item;
Node* leftChild;
Node* rightChild;
Node(Key, Item);
};
void BST::Insert(Key inputKey, Item inputItem)
{
Node* previousNode = nullptr;
if (root == nullptr)
{
root = new Node(inputKey, inputItem);
}
else
{
InsertRec(inputKey, inputItem, root, previousNode);
}
}
void BST::InsertRec(Key inputKey, Item inputItem, Node* & Current, Node* & previousNode)
{
if (Current != nullptr)
{
previousNode = Current;
}
bool isLeft = false;
if (!isLeaf(Current))
{
if (inputKey > Current->key)
{
isLeft = false;
InsertRec(inputKey, inputItem, Current->rightChild, previousNode);
}
else if (inputKey < Current->key)
{
isLeft = true;
InsertRec(inputKey, inputItem, Current->leftChild, previousNode);
}
else
{
Current->item = inputItem;
}
}
else
{
Current = new Node(inputKey, inputItem);
if (isLeft)
{
previousNode->leftChild = Current;
}
else
{
previousNode->rightChild = Current;
}
}
}
BST::Item* BST::Lookup(Key soughtKey)
{
Item* Item = LookupRec(soughtKey, root);
std::string Display = /*std::to_string(soughtKey) + ": " + */ *Item;
std::cout << Display << std::endl;
return Item;
}
BST::Item* BST::LookupRec(Key soughtKey, Node* currentNode)
{
if (!isLeaf(currentNode))
{
if ((currentNode->key > soughtKey))
{
LookupRec(soughtKey, currentNode->leftChild);
}
else if ((currentNode->key < soughtKey))
{
LookupRec(soughtKey, currentNode->rightChild);
}
else
{
return ¤tNode->item;
}
}
else
{
return nullptr;
}
}
bool BST::isLeaf(Node* n)
{
if (nullptr == n)
{
return true;
}
else
{
return false;
}
}
BST::BST()
{
}
BST::Node::Node(Key K, Item I)
{
key = K;
item = I;
leftChild = nullptr;
rightChild = nullptr;
}
And finally my header file for the binary search tree:
#pragma once
#include "iostream"
#include "string"
class BST
{
public:
using Key = int;
using Item = std::string;
void Insert(Key, Item);
Item* Lookup(Key);
BST();
private:
struct Node;
Node* root = nullptr;
static bool isLeaf(Node*);
static Item* LookupRec(Key, Node*);
static void InsertRec(Key, Item, Node* &, Node* &);
};
Any help would be greatly appreciated. I've been stuck on this for too long and I cannot progress without fixing this first.
The Test.txt file is filled with keys and items that are read and inputted like how I do it manually at the start of my main function, so I dont think the error is the file data.
Thanks in advance
UPDATE: Have finally found the error. The problem was with the bool isLeft in my InsertRec function. The bool was always false due to the recursion so have changed the code to compare previousNode->Key with Current->Key to determine if the child goes left or right
I have written code to reverse singly linked list using recursion. It is working fine on lists of length less than or equal to 174725. But on lists of length greater than 174725 it gives a segmentation fault(Segmentation fault: 11) while reversing it via reverse() call. Can someone please explain this to me ?
#include <iostream>
using namespace std;
class Node
{
public:
int val;
Node *next;
};
class Sll
{
public:
Node *head;
private:
void reverse(Node *node);
public:
Sll();
void insert_front(int key);
void reverse();
void print();
};
void Sll::reverse(Node *node)
{
if (node == NULL) return;
Node *rest = node->next;
if (rest == NULL)
{
head = node;
return;
}
reverse(rest);
rest->next = node;
node->next = NULL;
return;
}
Sll::Sll()
{
head = NULL;
}
void Sll::insert_front(int key)
{
Node *newnode = new Node;
newnode->val = key;
newnode->next = head;
head = newnode;
return;
}
void Sll::print()
{
Node *temp = head;
while (temp)
{
temp = temp->next;
}
cout << endl;
return;
}
void Sll::reverse()
{
reverse(head);
return;
}
int main()
{
Sll newList = Sll();
int n;
cin >> n;
for (int i = 0; i < n; i++) newList.insert_front(i + 1);
newList.reverse();
// newList.print();
return 0;
}
List reversing function must be tail-recursive, otherwise it is going to overflow the stack when recursing over a long list, like you observe. Also, it needs to be compiled with optimisations enabled or with -foptimize-sibling-calls gcc option.
Tail-recursive version:
Node* reverse(Node* n, Node* prev = nullptr) {
if(!n)
return prev;
Node* next = n->next;
n->next = prev;
return reverse(next, n);
}
An iterative list reversion can be more easily inlined though and it does not require any optimization options:
inline Node* reverse(Node* n) {
Node* prev = nullptr;
while(n) {
Node* next = n->next;
n->next = prev;
prev = n;
n = next;
}
return prev;
}
I am trying to make an insertion method for an Avl tree but the structure and order of my nodes turns out to be incorrect. I am having trouble finding where i am going wrong.
Here are my methods
Any sort of help would be appreciated
template
void AvL<T>::insert(string val, T k)
{
if (head == NULL) {
head = new AvLNode<T>(val, k);
} else {
put(head, val, k);
}
}
template <class T>
void AvL<T>::put(AvLNode<T>* root,string val,T key1) {
if (root->key > key1) {
if (root->left != NULL) {
put(root->left, val, key1);
Balance(root, key1);
} else {
root->left = new AvLNode<T>(val, key1);
root->bf = nodeHeight(root->left) - nodeHeight(root->right);
root->left->parent = root;
}
} else {
if (root->right != NULL) {
put(root->right, val, key1);
Balance(root, key1);
} else {
root->right = new AvLNode<T>(val, key1);
root->bf = nodeHeight(root->left) - nodeHeight(root->right);
root->right->parent = root;
}
}
}
template<class T>
void AvL<T>::Balance(AvLNode<T>* root, T key1)
{ root->bf = nodeHeight(root->left) - nodeHeight(root->right);
if (root->bf < -1 && key1 > root->right->key) {
cout << "here1 ";
LeftRotate(root);
} else if (root->bf > 1 && key1 < root->left->key) {
cout << "here2 ";
RightRotate(root);
} else if (root->bf < -1 && key1 < root->right->key) {
RightRotate(root->right);
cout << "here3 ";
LeftRotate(root);
} else if (root->bf > 1 && key1 > root->left->key) {
LeftRotate(root->left);
cout << "here4 ";
RightRotate(root);
}
}
template<class T>
void AvL<T>::RightRotate(AvLNode<T>* node)
{
AvLNode<T>* node1 = node->left;
node->left = node1->right;
node1->right = node;
node->bf = nodeHeight(node->left) - nodeHeight(node->right);
node1->bf = nodeHeight(node1->left) - nodeHeight(node1->right);
node = node1;
}
template<class T>
void AvL<T>::LeftRotate(AvLNode<T>* node)
{
AvLNode<T>* node1 = node->right;
node->right = node1->left;
node1->left = node;
node->bf = nodeHeight(node->left) - nodeHeight(node->right);
node1->bf = nodeHeight(node1->left) - nodeHeight(node1->right);
node = node1;
}
template<class T>
int AvL<T>::nodeHeight( AvLNode<T> *n)
{
int lheight=0;
int rheight=0;
int h = 0;
if (n == NULL)
{
return -1;
} else {
lheight = nodeHeight(n->left);
rheight = nodeHeight(n->right);
h = 1+max(lheight,rheight);
return h;
}
}
My .h file
template <class T>
struct AvLNode
{
string value;
T key;
AvLNode *parent; // pointer to parent node
AvLNode *left; // pointer to left child
AvLNode *right; // pointer to right child
int bf; // Balance factor of node
AvLNode(string Val, T k)
{
this->value = Val;
this->key = k;
this->parent = NULL;
this->left = NULL;
this->right = NULL;
bf = 0;
}
};
template <class T>
class AvL
{
AvLNode<T> *head;
public:
// Constructor
AvL();
// Destructor
~AvL();
// Insertion Function
void insert(string val, T k); // inserts the given key value pair into the tree
void Balance(AvLNode<T>* node, T key1);
void delete_node(T k); // deletes the node for the given key
void RightRotate(AvLNode<T>* node);
void LeftRotate(AvLNode<T>* node);
void put(AvLNode<T>* root,string val,T key1);
int nodeHeight(AvLNode<T> *n); // returns height of the subtree from given node
};
Your balance function is wrong. Since you've already inserted your new node into the tree, you don't need to worry about the key any more in Balance() - so the prototype should look like this:
template<class T>
void AvL<T>::Balance(AvLNode<T>* root);
The way you're doing it now seems to be attempting to balance based on the key you just inserted - which isn't necessary! You can balance the tree just based on the balance factors of nodes - here's how.
template<class T>
void AvL<T>::Balance(AvLNode<T>* root) {
if (root->bf > 1) {
if (root->left->bf == -1) LeftRotate(root->left);
RightRotate(root);
} else if (root->bf < -1) {
if (root->right->bf == 1) RightRotate(root->right);
LeftRotate(root);
}
}
You can read more about it here - but you seem to have the idea almost down. The only thing you need to change conceptually is the idea that you're balancing based on the key you just inserted. You're not - you're balancing based on the shape of the tree, which you can get from just the balance factors of each subtree.