why is the root value not being updated - c++

This is the code to find the ceil and floor in BST. When I am trying to insert the data. every time the insert call goes to the first if condition. i.e. though I pass the pointer. The value is not being updated in the main function. can some one tell me why is it so?
using namespace std;
struct Node
{
int key;
struct Node* right;
struct Node* left;
};
struct Node* newNode(int key)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->right = NULL;
newNode->left = NULL;
newNode->key = key;
return newNode;
}
void insert(struct Node** root,int key) {
if((*root) == NULL){
(*root)= newNode(key);
cout<<"entered first if condition"<<endl;
}
else if( (*root)->key <= key)
insert(&((*root)->left),key);
else
insert (&((*root)->right),key);
}
int ceil( struct Node* root , int input)
{
if (root == NULL)
return -1;
if(root->key == input)
return root->key;
if(root->key < input)
return ceil( root->right , input);
else{
int ceilnum = ceil(root->left, input);
return (ceilnum >= input) ? ceilnum : root->key;
}
}
int main()
{
int size, temp, ceilfor;
struct Node* root = NULL;
cout<< "size" << endl;
cin >> size;
for( int i = 0; i< size; i++)
{
cin >> temp;
insert(&root,temp);
}
cout<< root->key;
cout<< root->left->key;
cout << root->right->key;
cout << "ceil for" << endl;
cin >> ceilfor;
cout<< ceil(root, ceilfor) <<endl;
}

It has to come to the first condition (either directly or indirectly through recursive calls).
The actual insertion happens only in the first if block and other blocks will recursively reach the first if block.

Related

control insertion to BST according to user inputs

This is my code for binary search tree:
#include<iostream>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
node* createNode(int value)
{
node* newNode = new node;
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
node* insert( node* root, int data)
{
if (root == NULL) return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(node* root)
{
inorder(root->left);
cout<< root->data<<" ";
inorder(root->right);
}
int main()
{
node *root = NULL;
int n;
cout << "How many values do you want to enter" << endl;
cin >> n;
int no;
for (int i = 0; i < n; i++)
{
cin >> no;
insert(root, no);
}
inorder(root);
}
When I call display function/inorder in int main() it displays no values and the program stops with error
I am using loop to take input so it can take values upto to user specified value/range
but the display/inorder function is not working.
How can I resolve this issue?
In inOrder function you don't have stop condition!
and in the main should be root=insert(root, no);
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node* left;
struct node* right;
}node;
node* createNode(int value)
{
node* newNode = new node;
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
node* insert( node* root, int data)
{
if (root == NULL) return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(node* root)
{
if(root == NULL)return;
inorder(root->left);
cout<< root->data<<" ";
inorder(root->right);
}
int main()
{
node *root = NULL;
int n;
cout << "How many values do you want to enter" << endl;
cin >> n;
int no;
for (int i = 0; i < n; i++)
{
cin >> no;
root=insert(root, no);
}
inorder(root);
}

How to remove a certain node from a linked list by the data its holding?

We are suppose to enter a string, and then find where the string is in the linked list and remove that node
when i insert to the front of the list, so i enter data values a, b, c , d, when i print it it comes up as d,c,b,a. Now i insert to the rear of it, entering f and g, and the list now looks, d,c,b,a,f,g. I want to remove f but it just use the remove function it does not and still output the same list
using namespace std;
struct node {
string data;
node* next;
};
node* addFront(node* s);
node* addRear(node* s);
void remove(node* head, string abc);
void print(node* head);
int main() {
node* head = NULL;
cout << "Enter 5 data strings\n";
cout << "This will be inserted from the back\n";
for (int i = 0; i < 5; i++) {
head = addFront(head);
}
print(head);
cout << "Enter 3 strings and this will be inserted from the back of the orignal string\n";
for (int i = 0; i < 3; i++) {
head = addRear(head);
}
print(head);
cout << "Removing the head node\n";
string n;
cout << "Enter a string to remove\n";
cin >> n;
remove(head, n);
print(head);
}
node* addFront(node* s)
{
node* person = new node;
cin >> person->data;
person->next = s;
s = person;
return s;
}
node *addRear(node*s ) {
node* person = new node;
cin >> person->data;
person->next = NULL;
if (s == NULL) {
return person;
}
else {
node* last = s;
while (last->next != NULL) {
last = last->next;
}
last->next = person;
}
return s;
}
void remove(node* head, string a) {
node* previous = NULL;
node* current = head;
if (current == NULL) {
cout << "Value cannot be found\n";
return;
}
else {
while (previous != NULL) {
if (current->data == a) {
previous->next = current->next;
delete current;
break;
}
current = current->next;
}
}
}
void print(node * head)
{
node* temp = head;
while (temp != NULL) // don't access ->next
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
In remove function, previous is most certainly NULL when you hit that while loop.
Perhaps consider a do-while loop instead (with better handling of previous).
You may be better off handling the first node in a different manner since the holder of its previous is essentially the root pointer.

Making a circular linked list and finding the beginning of the loop

my assignment is to find the beginning of a loop in a circular linked list. Since the list is not provided i decided to make a liat by getting the user input for the size of the list then run a for loop with that size. The very last input (last node) is going to point somewhere in the linked list to create a cycle. My function to create the linked list is working, if i cout the head->data while getting the input from the user it prints the right value but when i call the function in the main the head pointer points to NULL and i get a segmentation fault. Can someone take a look at my code and explain why something like that is happening?
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
node *head = NULL;
node *tail = NULL;
node *slow = NULL;
node *fast = NULL;
int findLoop(node * head);
void getList(node * head, int listSize);
bool isEmpty(node * head);
int main(){
int listSize;
cout <<"\nEnter the size of the list: ";
cin >> listSize;
getList(head, listSize);
if(head != NULL){
cout << "\n\n\nprinting head " << head->data; //Seg Fault
}
else{
cout << "Head is NULL" << endl;
}
findLoop(head);
return 0;
}
int findLoop(node *head){
slow = head;
fast = head;
if(head == NULL){
cout << "\nThe list is empty\n";
}
bool isLoop = false;
while(slow != NULL && fast != NULL){
if(slow == fast && isLoop == false){
slow = head;
isLoop = true;
}
else if(slow == fast && isLoop == true){
cout <<"\nThe loop starts at: ";
return slow->data;
}
slow = slow->next;
fast = fast->next->next;
}
cout <<"\nThere is no loop\n";
return 0;
}
void getList(node * head, int listSize){
int userData;
for(int i=0; i<listSize; i++){
node *temp = new node;
cout <<"\nEnter a number: ";
int NodeValue = 0;
cin >> NodeValue;
temp->data = NodeValue;
if(head == NULL){
head = temp;
cout << head->data << endl; //Test for appropriate pointing.
}
if(tail != NULL){
tail->next = temp;// point to new node with old tail
}
tail = temp;// assign tail ptr to new tail
temp->next = tail;
if(i == listSize-1){
node *temp2;
temp2 = head;
int iNumber = rand() % i;
for(int j=0; j<iNumber; j++){
temp2 = temp2->next;
}
tail->next = temp2;
}
}
}
Minimal change to actually return new list would be passing pointer by reference:
void getList(node*&, int );
or better do define pointer type
using nodePtr = node*;
void getList(nodePtr&, int);

Linked List Program error in C++

I tried implementing Linked List using C++ using a structure.
I've included three functions - Size, Insertion and Deletion from the end.
The program compiled successfully. During execution, when I tried to give input for the LLInsert() function, there was just a cursor blinking on my execution window. I don't know if the function returned to main.
Also the LLSize() doesn't return 0 when I try to find the Size of a empty list.
I can't seem to figure out what I'm doing wrong. Here is my code.
#include<iostream>
using namespace std;
struct LL {
LL *next = NULL;
int data;
};
int LLSize(LL *head) {
LL *current = new LL;
current = head;
int count = 0;
while(current != NULL) {
current = current -> next;
count ++;
}
return count;
}
void LLInsert(LL *head,int value) {
LL *current = new LL;
current = head;
LL *Newnode = new LL;
Newnode -> data = value;
Newnode -> next = NULL;
if(head == NULL) {
head = Newnode;
return;
}
while(current->next != NULL) {
current = current->next;
}
current->next = Newnode;
return;
}
int LLDelete(LL *head) {
LL *current = new LL;
current = head;
int deleteddata;
while(current->next->next != NULL) {
current = current->next;
}
current->next->data = deleteddata;
current->next = NULL;
return deleteddata;
}
int main() {
int choice;
LL *A;
while(1) {
cout << "1. Size\n2. Insert\n3. Delete\n4. Exit" << endl;
cout << "Enter a choice : ";
cin >> choice;
switch(choice) {
case 1 : {
cout << "\nLength = " << LLSize(A) << endl;
break;
}
case 2 : {
int value;
cout << "\nEnter the element to insert : ";
cin >> value;
LLInsert(A,value);
break;
}
case 3 : {
cout << LLDelete(A);
break;
}
case 4 : {
exit(0);
}
default : {
cout << "\nInvalid choice. Enter a valid choice " << endl;
break;
}
}
}
}
Don't use using namespace.
Create a type for the list and a type for the nodes
struct LL {
LL* next;
int data;
};
struct L {
LL* head;
};
Use references and don't allocate new memory in each function
int LLSize(L& list) {
LL *current = list.head;
Check if the head of the list is set and use nullptr
if (list.head == nullptr) {
Use an instance of the list and not a pointer
int main() {
int choice;
L A;
Use a debugger like gdb to analyze your program.
Clean up at the end. Delete memory you allocated with new. One delete for each new.

Output of c++ program not coming as expected

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;
}