The function doesn't add anything to my bst tree - c++

class node{
public:
int data;
node *left;
node *right;
};
class BFStree{
public:
void insert(int key);
void deleteNode(int key);
void inorderTraversal(node *temp);
void inorder();
node *root;
BFStree(){
root = NULL;
}
};
void BFStree::insert(int key){
node *temp = root;
while(temp!=NULL){
if(key>temp->data){
temp = temp->right;
}
else if(key<temp->data){
temp = temp->left;
}
else{
cout << "NOT ALLOWED TO HAVE SAME DATA" << temp->data << " " << key << endl;
}
}
node *temp2 = new node;
temp2->data = key;
cout << key << " inserted" << endl;
temp2->left = NULL;
temp2->right = NULL;
temp = temp2;
}
int main(){
BFStree t;
t.insert(7);
t.insert(3);
t.insert(21);
}
I am trying to use the above function to insert data into the bst tree but it doesn't do anything, even the root is NULL
but when I use the following function, the job is accomplished. I don't understand what I have done differently in the two codes. I am new to programming so I am having such bad doubts. Please help me clear it.
void BFStree::insert(int key){
node *temp = root;
if(temp==NULL){
temp = new node;
temp->data = key;
temp->left = NULL;
temp->right = NULL;
root = temp;
return;
}
while(1){
if(key>temp->data){
if(temp->right==NULL){
node *temp2 = new node;
temp2->data = key;
temp2->left = NULL;
temp2->right = NULL;
temp->right = temp2;
break;
}
else{
temp = temp->right;
}
}
else if(key<temp->data){
if(temp->left==NULL){
node *temp2 = new node;
temp2->data = key;
temp2->left = NULL;
temp2->right = NULL;
temp->left = temp2;
break;
}
else{
temp = temp->left;
}
}
}
}

The main problem in your first function is that you just iterate over the tree until you find a null, and after that you assign that null value to temp.
After that you create a new node and assign temp the reference of new node. But your temp node is not connected to the tree. And there is no connection between the temp node and its parent or root node of the tree.
Whereas in 2nd example :
if(temp->right==NULL){
node *temp2 = new node;
temp2->data = key;
temp2->left = NULL;
temp2->right = NULL;
temp->right = temp2;
break;
}
This is the key, you store the reference of your newly created node in the right or left child of its parent node.

Related

Segmentation fault during deleting a node from the end of doubly linked list

I am trying to delete a node from the end of the doubly linked list,but i am getting:
segmentation fault
i have added different functions to add the node, from beginning , from end , and at any position.I checked the insertion of nodes,its working fine,the DLL is displayed correctly,but when it comes to deleting function,it gives segmentation fault.
struct Node {
Node* left;
Node* right;
int data;
};
Node* head = NULL;
void insertion_At_End(int element) {
Node* ptr = head;
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->data = element;
if(head==NULL) {
head = temp;
} else {
while(ptr->right!=NULL) {
ptr = ptr->right;
}
temp->left = ptr->right;
ptr->right = temp;
}
}
void insertion_At_Beg(int element) {
Node* ptr = head;
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->data = element;
if(head==NULL) {
head = temp;
} else {
temp->right = ptr;
ptr->left = temp;
head = temp;
}
}
void insertion_At_Pos(int element , int position , int length) {
Node* ptr;
Node* temp = new Node;
temp->left = temp->right = NULL;
temp->data = element;
int counter = 1;
if(position==1) {
insertion_At_Beg(element);
}
else if(position==length) {
insertion_At_End(element);
}
else {
ptr = head;
while(counter!=(position-1)) {
ptr = ptr->right;
counter++;
}
temp->right = ptr->right;
ptr->right->left = temp;
temp->left = ptr;
ptr->right = temp;
}
}
void deletion_At_End() {
Node *ptr = head;
while(ptr->right!=NULL) {
ptr = ptr->right;
}
ptr->left->right=NULL;
delete ptr;
}
I get the error if i have only one element in the list. When you have only one element in the list you can not set what it is in its left's right pointing to NULL because it does not exist! This works for me:
void deletion_At_End() {
Node *ptr = head;
while(ptr->right!=NULL) {
ptr = ptr->right;
}
if(ptr->left == NULL){
delete ptr;
}
else{
ptr->left->right=NULL;
delete ptr;
}
}

Getting " expected a ; " error message in C++

I am implementing Binary search tree in C++. I have written the following code but for some reason I get an error message that says:
expected a ;
I get above message when compiling the code.
Also I am new to C++ and I would appreciate a lot if I get some help on this one.
Some context to Binary Search Tree:
Binary search trees keep their keys in sorted order, so that lookup
and other operations can use the principle of binary search: when
looking for a key in a tree (or a place to insert a new key), they
traverse the tree from root to leaf, making comparisons to keys stored
in the nodes of the tree and deciding, on the basis of the comparison,
to continue searching in the left or right subtrees. On average, this
means that each comparison allows the operations to skip about half of
the tree, so that each lookup, insertion or deletion takes time
proportional to the logarithm of the number of items stored in the
tree. This is much better than the linear time required to find items
by key in an (unsorted) array, but slower than the corresponding
operations on hash tables.
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *left, *right, *parent;
};
Node* DeleteNode(Node *root, int data);
void find_min(Node *root);
void inorder(Node *x);
void Insert(Node *root, int data);
//delete a node
//search_tree
//insert a node
//temp->parent = NULL;
int main()
{
Node *root, *temp;
//node with 20
temp = new Node;
temp->data = 20;
temp->left = NULL;
temp->right = NULL;
root = temp;
//node with 10
temp = new Node;
temp->data = 10;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->left = temp;
temp->parent = root;
//node with 30
temp = new Node;
temp->data = 30;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->right = temp;
temp->parent = root;
//node with 25
temp = new Node;
temp->data = 25;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->right->left = temp;
temp->parent = root->right;
//node with 40
temp = new Node;
temp->data = 40;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->right->right = temp;
temp->parent = root->right;
//node with 2
temp = new Node;
temp->data = 2;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->left->left = temp;
temp->parent = root->left;
//node with 15
temp = new Node;
temp->data = 15;
temp->left = NULL;
temp->right = NULL;
temp->parent = NULL;
root->left->right = temp;
temp->parent = root->left;
find_min(root);
cout << "Printing numbers in order" << endl;
inorder(root);
cout << "printing in-order of the given root" << endl;
delete(root);
}
void find_min(Node *root)
{
Node *temp;
temp = root;
while (temp->left != NULL)
temp = temp->left;
cout << "min number is " << temp->data << endl;
}
void inorder(Node *x)
{
if (x != NULL)
{
inorder(x->left);
cout << x->data << endl;
inorder(x->right);
}
}
Node* DeleteNode(Node *root, int data)
{
if (root->data == NULL) {
return root;
}
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
else if (data < root->data)
root->left = DeleteNode(root->left, data);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if (data > root->data)
root->right = DeleteNode(root->right, data);
// case 1: No child
else if (root->left == NULL & root->right == NULL)
delete root;
return root;
//data < root->data struct Node *temp = root;
// case 2: one child
if (root->left == NULL){
Node *temp = root;
root = root->right;
delete temp;
return root;
}
//
else if (root->right == NULL) {
Node *temp = root;
root = root->left;
delete temp;
return root;
}
// case 3: two child
else (root == root->right){
root->data = temp->data;
root->right = DeleteNode(root->right, temp->data);
return root;
}
}
This is your issue: else (root == root->right){. If you want to make that a condition, you'll need to use else if(root == root->right)
Note that per Godbolt, you have more errors even with that fix (they look simple to fix).

Doubly linked list seg faults

I am trying to display a doubly linked list backwards, but every time I try to run anything even remotely touching the "prev" pointer in the program I get a seg fault.
I've been trying to figure this out for about 4 hours now and I just can't seem to pin it down. I can't tell if the issue is coming from my print backwards function or from the actual prev pointers themselves.
#include <iostream>
#include "list.h"
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
};
bool LinkedList::addAtBeginning(int val){
Node *upd8L = head; // This Node will update Last
Node *upd8 = head;; // This Node will update the previous pointers
Node *point = new Node(); // This Node will insert the new node at the beginning
point->data=val; // This sets the data in the new node
point->next=head; // This sets the next pointer to the same as head
head = point; // This sets the head to the new Node
while(upd8){
upd8 = upd8->next;
upd8->prev = upd8L;
upd8L=upd8L->next;
}
return true;
};
bool LinkedList::remove(int val){
Node *temp = head;
Node *trail = 0;
while(temp != NULL){
if(temp->data == val){
if(temp->next == head->next){
head = head->next;
}else{
trail->next = temp->next;
}
delete temp;
}
trail = temp;
temp = temp->next;
}
return true;
};
void LinkedList::printForward() const{
Node *temp;
temp = head;
while(temp){
cout << temp -> data << endl;
temp = temp->next;
}
};
void LinkedList::printBackward() const{
Node *temp = head;
while(temp){
temp = temp->next;
cout << temp->data << endl;
}
while(temp){
cout << temp->data;
cout << "Pop" << endl;
temp = temp-> prev;
}
};
If possible, I'd love an explanation as to what is bugging up my program rather than just a straight answer, I want to know what I'm doing wrong and why it's wrong.
Thank you!
edit
Here's list.h
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
class LinkedList
{
private:
struct Node
{
int data;
Node * next;
Node * prev;
};
Node * head, * tail;
public:
LinkedList();
bool addAtBeginning(int val);
bool remove(int val);
void printForward() const;
void printBackward() const;
};
#endif
The function printBackward() may cause a seg-fault in the last iteration of the loop. while(temp) means iterate till you get the element out of the list NULL. Then you assigning temp = temp->next where temp->next is NULL. Now when you are calling cout << temp->data << endl; you are trying to get data from NULL pointer. Try to change the order. First display the node data, then change the temp pointer. An example:
void LinkedList::printBackward() const{
Node *temp = head;
while(temp){
cout << temp->data << endl;
temp = temp->next;
}
What you are doing wrong is getting the data from a NULL pointer.
So, I figured it out after a ton of trial and error!
The biggest issue I was having that kept giving me segmentation errors was whenever I was removing elements of the list I was failing to update the "prev" part of the node, and as a result any time I tried to read the list backwards I was getting a seg error.
//put your implementation of LinkedList class here
#include <iostream>
#include "list.h"
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
};
bool LinkedList::addAtBeginning(int val){
Node *point = new Node(); // This Node will insert the new node at the beginning
point->data=val; // This sets the data in the new node
point->next=head; // This sets the next pointer to the same as head
head = point; // This sets the head to the new Node
if(head->next != NULL){
Node *temp = head->next;
temp->prev = head;
}
return true;
};
bool LinkedList::remove(int val){
Node *temp = head->next;
Node *trail = head;
if(head->data ==val){
head = head->next;
head->prev = NULL;
delete trail;
}else{
while(temp != NULL){
if(temp->data == val){
if(temp->next != NULL){
trail->next = temp->next;
delete temp;
temp= temp->next;
temp->prev=trail;
}else{delete temp;
trail->next = NULL;
}
}
trail = temp;
temp = temp->next;
}
}
return true;
};
void LinkedList::printForward() const{
Node *temp;
temp = head;
while(temp){
cout << temp->data << endl;
temp = temp->next;
}
};
void LinkedList::printBackward() const{
Node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
while(temp->prev != NULL){
cout << temp->data << endl;
temp = temp->prev;
}
cout << head->data << endl;
};

Singly Linked List Infinite Loop

It's been a week since i started learning about linked list and i only managed to learn about singly linked list. So today i implemented the linked list which i learned in c++ and while i tried to run it the code goes into an infinite loop of some random numbers. I tried debugging the code but i coudn't find whats so ever is wrong with the code. The code is below. Help is appreciated.Thanks
#include <iostream>
using namespace std;
struct node{
int data;
node * next;
};
class singly{
private:
node * head,*tail;
public:
singly(){
head=NULL;
tail=NULL;
}
void createNode(int value){
node * temp = new node;
temp->data=value;
temp->next=NULL;
if(head==NULL){
head=temp;
tail=temp;
temp=NULL;
}
else{
tail->next=temp;
tail=temp;
}
}
void display(){
node * temp = new node;
head=temp;
while(temp!=NULL){
cout << temp->data << "\t" << endl;
temp->next=temp;
}
}
void insert_end(int value){
node*newnode = new node;
node*temp = new node;
newnode->data=value;
newnode->next=NULL;
temp=head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next=newnode;
}
void delete_node(){
node*current = new node;
node*previous = new node;
current = head;
while(current->next!=NULL){
previous=current;
current=current->next;
}
tail=previous;
previous->next=NULL;
delete current;
}
};
int main(){
singly lists;
lists.createNode(32);
lists.createNode(654);
lists.createNode(34);
lists.createNode(234);
cout<<"\n--------------------------------------------------\n";
cout<<"---------------Displaying All nodes---------------";
cout<<"\n--------------------------------------------------\n";
lists.display();
cout<<"\n--------------------------------------------------\n";
cout<<"-----------------Inserting At End-----------------";
cout<<"\n--------------------------------------------------\n";
lists.createNode(55);
lists.display();
cout<<"\n--------------------------------------------------\n";
cout<<"-----------------Deleing At End-------------------";
cout<<"\n--------------------------------------------------\n";
lists.delete_node();
lists.display();
}
The member function display does not make sense.
It overwtites the data member head with uninitialized newly created temp.
node * temp = new node;
head=temp;
so the function invokes undefined behavior.
The function can look like
void display()
{
for ( node * temp = head; temp != nullptr; temp = temp->next )
{
cout << temp->data << "\t";
}
}
Or it is better to define it the following way
std::ostream & display( std::ostream &os = std::cout )
{
for ( node * temp = head; temp != nullptr; temp = temp->next )
{
os << temp->data << "\t";
}
return os;
}
The data member insert_end is also wrong. It does not take into account that head and tail can be equalto nullptr and does not change them.
The function can be defined the following way
void insert_end(int value)
{
node *newnode = new node { value, nullptr };
if ( tail == nullptr )
{
head = tail = newnode;
}
else
{
tail = tail->next = newnode;
}
}
The member function delete_node firstly does not make sense for a singly-linked list and again is wrong and invokes undefined behavior. The function should remove the first node from the list.
Nevertheless if you want to remove the last node from the list then the function can look like
void delete_node()
{
if ( head != nullptr )
{
tail = nullptr;
node *current = head;
while ( current->next )
{
tail = current;
current = current->next;
}
if ( tail == nullptr )
{
head = tail;
}
else
{
tail->next = nullptr;
}
delete current;
}
}
For starters, display() is wrong. You want the update to be temp = temp->next; and it can also be initialized as node * temp = head hence not requiring the second line.
Your delete_node() can be re-written to:
if (head->next == NULL) // handles the case that it consists of 1 element
{
delete head;
head = NULL;
}
else
{
node *nextToEnd = head;
node *end = head->next;
while (end->next != NULL)
{
nextToEnd = end;
end = end->next;
}
delete end;
nextToEnd->next = NULL;
}
As stated in the comments, review the use of the new keyword

I am trying to add at the back of the linked list but i keep getting segmentation error, can someone explain why?

//creaing a linked list
#include <stdio.h>
#include <iostream>
using namespace std;
struct node {
int data;
node *next;
};
node *head = NULL;
node *tail = NULL;
This is to add to the front of the linked list
void addToFront(int insert){
node *temp = new node();
temp->data = insert;
temp->next = head;
head = temp;
}
This will transverse the linked list
void Transverse(){
node *temp1 = new node();
temp1 = head;
while(temp1!=NULL){
cout << temp1->data << endl;
temp1 = temp1 ->next;
tail = temp1;
}
}
This is the part of the code I am having problems with by add to the back function
void addToBack(int insert){
node * temp = new node();
temp -> data = insert;
temp -> next = NULL;
if(head==NULL){
head=temp;
}
else{
node * temp2= new node();
while(temp2!=NULL){
temp2 = temp2 -> next;
}
temp2->next= temp;
}
}
int main(){
addToBack(4);
addToFront(1);
addToFront(2);
addToFront(3);
addToBack(4);
Transverse();
return 0;
}
In the else branch you might want this:
node * temp2 = head;
while(temp2->next != NULL){
temp2 = temp2 -> next;
}
temp2->next= temp;