Inserting in Binary Search Tree (C) using for loop - c

I'm having trouble inserting in a Binary Search Tree using for loop, when I call the InorderTraversal function, there is no output all I get is a blank line, as far as I think rest of the code is okay the only problem is in the insert function.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct BinaryTree{
int data;
struct BinaryTree *left;
struct BinaryTree *right;
} node;
node* Insert(node* head, int value)
{
_Bool flag = true;
for(node *temp = head; flag == true; (temp = (value >= temp->data)?(temp->right):(temp->left)))
{
if(temp == NULL)
{
temp = (node*)malloc(sizeof(node*));
temp->data = value;
temp->left = NULL;
temp->right = NULL;
flag = false;
}
}
return head;
}
void InorderTraversal(node* head)
{
if(head == NULL)
{
return;
}
InorderTraversal(head->left);
printf("%d ",head->data);
InorderTraversal(head->right);
}
int main(void)
{
node *head = NULL;
for(int i = 0; i < 40; i++)
{
head = Insert(head,i);
}
InorderTraversal(head);
return 0;
}

Here try these changes in your Insert function
node* Insert(node *head, int value)
{
if(!head) //Explicitly insert into head if it is NULL
{
head = malloc(sizeof *head);
head->data = value;
head->left = NULL;
head->right = NULL;
return head;
}
for(node *temp = head,*temp2 = head; ;(temp = (value >= temp->data)?(temp->right):(temp->left)))
{
if(temp == NULL)
{
temp = malloc(sizeof *temp);
temp->data = value;
temp->left = NULL;
temp->right = NULL;
if(value >= temp2->data) //update previous nodes left or right pointer accordingly
temp2->right = temp;
else
temp2->left = temp;
break;
}
temp2 = temp; //Use a another pointer to store previous value of node
}
return head;
}

Call me crazy, but shouldn't that malloc(sizeof(node*)) be malloc(sizeof node)?
I am not that so informed, other than being able to read C, so excuse me if this is simply wrong...
Edit: ... or malloc(sizeof * temp)

When you insert the first node you dereference an uninitialized pointer here:
temp->data
Where temp is head and head in uninitialized and pointing to NULL.
So you first have to make special case when head is NULL:
if( !head )
{
head = malloc(sizeof(node));
head->data = value;
head->left = NULL;
head->right = NULL;
return head ;
}
When you continue adding elements you don't update the pointer of the last node. Your for loop should have an extra pointer to the previous node and when you get to the last node and find NULL update the previous nodes left or right pointer.
if(temp == NULL) //wrong, should be: not equal
{
temp = (node*)malloc(sizeof(node*)); //wrong, should be: sizeof the node not the pointer
temp->data = value;
temp->left = NULL;
temp->right = NULL;
flag = false; //use break instead
}
here the previous node pointer left or right is not updated and when you search you can't find any node.

Related

unable to insert into ordered linked list in C

i am new to programming and C. I am trying to create an ordered linked list. For some reason which i cannot figure out, it never enters the first if block in the insert_in_order function even though my linked list is empty when i call the insert_in_order function. Would anyone have any idea what i am doing wrong?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
typedef struct node node_t;
void printlist(node_t *head){
node_t *temporary = head;
while(temporary != NULL){
printf("%d - ", temporary->value);
temporary = temporary->next;
}
printf("\n");
}
node_t *create_new_node(int value){
node_t *result = malloc(sizeof(node_t));
result->value = value;
result->next = NULL;
//printf("result.value = %d\n", result->value);
return result;
}
void insert_in_order (node_t *head, node_t *node_to_insert){
node_t *current_node = head;
node_t *prior_node = head;
//linked list is empty
if (head == NULL){ //never enters if block for some reason
head->next = node_to_insert;
node_to_insert->next = NULL;
break;
//printf("inside the if stmt");
}
if(node_to_insert->value <= current_node->value){
head->next = node_to_insert;
node_to_insert->next = current_node;
break;
}
current_node = current_node->next;
while (current_node->next != NULL){
if(node_to_insert->value <= current_node->value){
node_to_insert->next = current_node;
prior_node->next = node_to_insert;
break;
}
else if (node_to_insert > current_node){
current_node = current_node->next;
prior_node = prior_node->next;
}
}
//node to insert is the largest in the linked list
current_node->next = node_to_insert;
node_to_insert->next = NULL;
}
int main(){
node_t *head;
node_t *node1;
node_t *node2;
head = NULL;
node1 = create_new_node(22);
node2 = create_new_node(33);
printf("node1's value equals %d\n", node1->value);
printf("node2's value equals %d\n", node2->value);
insert_in_order(head, node1);
printlist(head);
}
First of all this code does not compile - these breaks are invalid
if (head == NULL){ //never enters if block for some reason
head->next = node_to_insert;
node_to_insert->next = NULL;
break; <<<<====
//printf("inside the if stmt");
}
and
if (node_to_insert->value <= current_node->value) {
head->next = node_to_insert;
node_to_insert->next = current_node;
break; <<<=====
}
Seems like you meant return when you said break, now compiles with those replaced by return
Now this goes wrong
//linked list is empty
if (head == NULL) { //never enters if block for some reason
head->next = node_to_insert;
You just tested to see if head is NULL and if it is you try to use it, thats never going to work
You mean this
//linked list is empty
if (head == NULL) { //never enters if block for some reason
head = node_to_insert;
node_to_insert->next = NULL;
return;
}
code now runs to completion, although there may be other errors
node1's value equals 22
node2's value equals 33

Inserting elements in a linked list in various indices using one function only

This is the code I tried writing down to add an element in a double linked list, that takes an index and a value and adds a new element to the original list.
It is taking index and value but just adds the elements I give like a stack.
node *add(node *head, int index, int val)
{
node *new = create(val);
node *temp = malloc(sizeof(node));
if (head == NULL)
{
head = new;
temp = head;
//printf(": %d",temp->data);
}
temp = head;
int i = 1;
while (i < (index - 1) && (temp->next != NULL))
{
i++;
temp = temp->next;
}
temp->next = new;
new->next = NULL;
new->prev = temp;
return head;
}
however this code(for a doubly linked list) just adds elements one after the other, disregarding the index passed.
My prof gave us a code for a singly linked list where he did something similar.
struct Node *insert(struct Node *listp, int pos, int info)
{
/*Inserts a Node in list at position pos with data info
pos>0. If pos>list length then new node added at end.
If pos<1 adds at beginning.
*/
struct Node *new=malloc(sizeof(struct Node)), *prev;// new is the new node we create everytime.
//create new node and initialize fields
new->data=info;
new->next=NULL;
if (listp==NULL) listp=new;
else
if (pos<=1) { //negative or 1 index.
new->next=listp; //first node bann gaya new
listp=new; //head is pointing at new
}
else {
//pos>1. Go to node at pos-1.
prev=listp;
int i=1;
while ((i++<pos-1) && prev->next!=NULL) { //indexing
prev=prev->next;
}
new->next=prev->next;
prev->next=new;
}
return listp;
}
how do I address this problem?
To implement a doubly linked list, your node needs to have pointers to the previous node and next node, then you can write something almost as similar to what your professor gave you for single linked list:-
#include <stdlib.h>
#include <stdio.h>
//Doubly linked list Node
typedef struct Node{
int info;
struct Node* next;
struct Node* prev;
} Node;
Node* insert(Node* listp, int pos, int info){
//Allocate memory for node and its previous neighbor
Node* new = malloc(sizeof(Node));
Node* prev = malloc(sizeof(Node)), *tail;
//initialize new node with these values
new->info = info;
new->next = NULL;
new->prev = NULL;
//if head doesn't exist then create one
if(listp == NULL){
/*
listp gets whatever new had, ie
listp->info = info
listp->next = NULL
listp->prev = NULL
*/
Node* tail = malloc(sizeof(Node));
tail->info = 0;
tail->next = NULL;
tail->prev = NULL;
listp = new;
listp->next = tail;
tail->prev = listp;
}
//Lets Loop through the List and insert node at pos
else {
if(pos <= 1){
/*
This should replace the current head
listp = new
*/
new->next = listp;
new->prev = listp->prev;
listp->prev = new;
listp = new;
}
else{
int i = 2;
prev = listp->next;
printf("%d\n", prev->prev->info);
while(i != pos){
printf("%d\n", new->info);
prev = prev->next;
i++;
}
new->next = prev;
new->prev = prev->prev;
prev->prev->next = new;
prev->prev = new;
}
}
return listp;
}
// Test case
int main(){
Node* listp;
listp = insert(NULL, 0, 2);
listp = insert(listp, 1, 3);
listp = insert(listp, 2, 5);
Node* cnt = listp;
printf("|");
while(cnt->next != NULL){
printf("--%d-->", cnt->info);
cnt = cnt->next;
}
printf("\n");
}
Try that. Make any typo corrections if any
#include <stdio.h>
#include <stdlib.h>
/**
* add_node_end - adds a new node at the end of a dllist list
* #head: head of linked list
* #n: integer value of node
*
* Return: address of new element, NULL if fails
*/
node *add_node_end(node **head, const int n)
{
node *new, *temp;
new = malloc(sizeof(node));
if (new == NULL)
return (NULL);
new->n = n;
new->next = NULL;
if (*head == NULL)
{
new->prev = NULL;
*head = new;
return (*head);
}
temp = *head;
while (temp->next)
{
temp = temp->next;
}
temp->next = new;
new->prev = temp;
return (new);
}
/**
* add_dnodeint - adds a new node at the beginning of a dlistint_t list
* #head: head of linked list
* #n: integer value of node
*
* Return: address of new element, NULL if fails
*/
node *add_node_start(node **head, const int n)
{
node *new;
new = malloc(sizeof(node));
if (new == NULL)
return (NULL);
new->n = n;
new->prev = NULL;
if (*head == NULL)
{
new->next = NULL;
*head = new;
return (*head);
}
new->next = *head;
(*head)->prev = new;
*head = new;
return (*head);
}
/**
* node_len - returns the number of elements in a dllist list
* #h: head of doubly linked list
*
* Return: number of nodes
*/
size_t node_len(const node *h)
{
int count = 0;
while (h)
{
count++;
h = h->next;
}
return (count);
}
/**
* insert_dnodeint_at_index - inserts a new node at a given position
* #h: a pointer to a pointer of the first node of node linked list
* #index: the position to add the new node
* #val: the data n of the new node
* Return: if the function fails = NULL
* otherwise - the address of the new node/element
*/
node *insert_dnodeint_at_index(node **h, unsigned int index, int val)
{
node *newNode, *current;
size_t list_length;
unsigned int i = 0;
if (h == NULL)
return (NULL);
if (index == 0)
return (add_node_start(h, n));
list_length = node_len(*h);
if (index == (list_length - 1))
return (add_node_end(h, n));
newNode = malloc(sizeof(node));
if (newNode == NULL)
return (NULL);
newNode->val = val;
if (*h == NULL)
{
newNode->prev = NULL;
newNode->next = NULL;
return (newNode);
}
current = *h;
while (current)
{
if (i == index)
{
newNode->next = current;
newNode->prev = current->prev;
current->prev->next = newNode;
current->prev = newNode;
return (newNode);
}
current = current->next;
i++;
}
free(newNode);
return (NULL);
}

Circular linked list crashes when displayed

I'm trying to make a circular linked list. When I try to display the list after creating it, the program keeps on crashing. Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node * next;
} node;
node * createList(int);
void display(node * head);
int main() {
struct node * head;
head = createList(5);
display(head);
}
node * createList(int n) {
int i = 0,data = 0;
struct node * head = NULL;
struct node * temp = NULL;
struct node * p = NULL;
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
temp->next = head;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
void display(node * head) {
struct node * temp = head->next;
while (temp != head) {
printf("%d-> \t",temp->data);
temp = temp->next;
}
printf("\n");
}
What am I doing wrong?
You have set every temp's next to head in temp->next = head; but did it too early (the first is just NULL). Then you tested p->next against NULL in while (p->next != NULL) { but you should have tested against head. Alternatively, you can continue to test against NULL but then you need to initialize temp->next to NULL and assign head to temp->next only after the for loop.
Your display code started from the second link.
Here is a fixed code using the first option in 1. above:
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != head) {
p = p->next;
}
p->next = temp;
}
temp->next = head;
}
Here is a fixed code using the alternative option in 1. above. You still need to initialize temp->next to NULL since malloc() does not initialize.
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
if (temp != NULL) {
temp->next = head;
}
But in reality, there is no need to "walk" from the head on every creation. You can simply keep the previous and link it to the next:
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
temp->data = data++;
if (head == NULL) {
head = p = temp;
} else {
p = p->next = temp;
}
}
if (temp != NULL) {
temp->next = head;
}
Here is a fix for the display():
void display(node * head) {
struct node * temp = head;
if (temp != NULL) {
do {
printf("%d-> \t",temp->data);
temp = temp->next;
} while (temp != head);
}
printf("\n");
}
The problem is on the first node you initialize:
struct node *head = NULL;
...
for (i = 0; i < n; i++) {
...
temp->next = head;
So tmp->next == NULL on the first iteration leaving head->next == NULL. That will not work for a circular list. When you attempt to insert the 2nd node:
p = head;
while (p->next != NULL) {
What was head->next again?? (oh, NULL) Dereferencing a NULL pointer (BOOM Segfault!)
Do your circular list correctly. On insertion of the first node set:
if (head == NULL) {
head = temp;
head->next = temp; /* you must set head->next to temp */
} ...
So on the insertion of the remaining nodes you simply need:
} else {
p = head;
while (p->next != head) { /* iterate to last node */
p = p->next;
}
p->next = temp; /* now set p->next = temp */
}
Now, you handle your display() function the same way, e.g.
void display (node *head)
{
if (!head) { /* validate list not empty */
puts ("(list-empty)");
return;
}
struct node *temp = head;
do { /* same loop problem fixed in display() */
printf ("%d-> \t", temp->data);
temp = temp->next;
} while (temp != head);
putchar ('\n');
}
If you make the changes, then you can test your list with:
int main (void) {
struct node *head, *tmp;
head = createList(5);
display (head);
puts ("\niterate from mid-list");
tmp = head;
tmp = tmp->next;
tmp = tmp->next;
display (tmp);
}
Example Use/Output
$ ./bin/lls_circular_fix
0-> 1-> 2-> 3-> 4->
iterate from mid-list
2-> 3-> 4-> 0-> 1->
Lastly, you are not multiplying the type node by head in struct node * head = NULL; Write it as struct node *head = NULL; (the same for all your function declarations as well) Much more readable.
When you go to delete a note from the list, you must create a special case for both head and tail (the last node). In this sense, the singly-linked list takes a bit more effort than a doubly-linked list due to not having a prev node pointer to track the prior node.
Look things over and let me know if you have questions.
A full example would be:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} node;
node *createList (int);
void display (node *head);
int main (void) {
struct node *head, *tmp;
head = createList(5);
display (head);
puts ("\niterate from mid-list");
tmp = head;
tmp = tmp->next;
tmp = tmp->next;
display (tmp);
}
node *createList (int n)
{
int i = 0,data = 0;
struct node *head = NULL;
struct node *temp = NULL;
struct node *p = NULL;
for (i = 0; i < n; i++) {
if (!(temp = malloc (sizeof *temp))) {
perror ("malloc-temp");
return NULL;
}
temp->data = data++;
temp->next = head; /* head is NULL on 1st node insertion */
if (head == NULL) {
head = temp;
head->next = temp; /* you must set head->next to temp */
} else {
p = head;
while (p->next != head) { /* iterate to last node */
p = p->next;
}
p->next = temp; /* now set p->next = temp */
}
}
return head;
}
void display (node *head)
{
if (!head) { /* validate list not empty */
puts ("(list-empty)");
return;
}
struct node *temp = head;
do { /* same loop problem fixed in display() */
printf ("%d-> \t", temp->data);
temp = temp->next;
} while (temp != head);
putchar ('\n');
}

How to avoid segfault when adding to a sorted linked list?

I need to create a new function when adding a new element, it places it in the list so that the list stays in sorted order. I am not sure if my implementation is correct, my first try, with my group members, gave a segmentation fault. When I tried to do it on my own, it did not do anything. Any help will be appreciated. Here is my code:
header file:
typedef struct s{
int value;
struct s *next, *previous;
} node, *node_ptr;
c file:
#include <stdio.h>
#include <stdlib.h>
#include "double.h"
void
print_list(node_ptr list) {
// walk the list to print out the contents
while (list) {
printf("%d ",list->value);
list = list->next;
}
printf("\n");
}
void delete_list(node_ptr list) {
// walk the list to delete the elements
node_ptr t;
while (list) {
t = list;
list = list->next;
free(t);
}
}
node_ptr new_node(int value) {
node_ptr t = (node_ptr)malloc(sizeof(node));
t->value = value;
t->next = t->previous = NULL;
return t;
}
node_ptr add_to_back(node_ptr list, int value) {
node_ptr t = list;
node_ptr s = new_node(value);
// special case: starting with an empty list
if (t == NULL) return s;
// at this point we know there is a least one element in
// the list
while (t->next != NULL) // walk the list looking for the last element
t = t->next;
// we are at the end so now we arrange the pointers
t->next = s;
s->previous = t;
return list;
}
// my implementation after some research
node_ptr add_sorted(node_ptr list, int value) {
node_ptr temp = list;
node_ptr newNode;
if(temp == NULL || temp->value < newNode->value)
{
newNode->next = temp;
temp = newNode;
}
else
{
while(temp != NULL && temp->value < value)
{
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
return newNode;
}
// second implementation with team
/*
node_ptr add_sorted2(node_ptr list, int value) {
// This is the function you need to implement
// when adding a new element place it in the list so that the list stays in sorted order.
node_ptr temp = list;
node_ptr n = new_node(value);
if(temp == NULL)
{
temp->value = value;
temp->next = NULL;
return n;
}
else if(temp->next != NULL) {
while(temp->next != NULL) {
if(temp->value <= value) {
n->next = temp->next;
temp->next = n;
return n;
}
else if(temp->value > value) {
temp = temp->next;
}
else {
temp->next = n;
return n;
}
}
}
return n;
}
*/
int
main() {
int in_val;
node_ptr my_list = NULL;
node_ptr sorted_list = NULL;
scanf("%d",&in_val);
while (in_val > 0) { // going to read input until see 0 or negative
my_list = add_to_back(my_list,in_val);
sorted_list = add_sorted(sorted_list,in_val);
scanf("%d",&in_val);
}
printf("List:\n");
print_list(my_list);
printf("Sorted List:\n");
print_list(sorted_list);
delete_list(my_list);
delete_list(sorted_list);
}
The segmentation fault is clear to me, you are using an uninitialized pointer here
if(temp == NULL || temp->value < newNode->value)
// ^
Or ANY OTHER newNode's dereference anywhere, because newNode is never initialized in your code.
If temp == NULL, and you didn't initialize newNode yet then undefined behavior.
Adding a node to a list while preserving order is easy,
Create the new node
If succeeded creating it, traverse the list until the next node is greater|smaller (depending on the ordering that you desire) than the new node.
When you find it, link current's node next to the new node and the next node should be new node's next.
And that is all.

Showing runtime error in printing

When i am printing linked list , i get runtime error
#include stdio.h
#include stddef.h
typedef struct
{
int info;
struct DEMO1 *next;
} DEMO1;
void insertatlast(DEMO1 * p, int o);
void printl(DEMO1 * p);
int main()
{
int temp;
DEMO1 *head = NULL;
if (head == NULL)
while (1)
{
printf("ENTER 0 to exit");
scanf("%d", &temp);
if (temp == 0)
break;
insertatlast(head, temp);
}
printl(head);
return 0;
}
void insertatlast(DEMO1 * head, int data)
{
if (head == NULL)
{
DEMO1 *node = (DEMO1 *) (malloc(sizeof(DEMO1)));
node->info = data;
node->next = 0;
head = node;
}
else
{
DEMO1 *temp;
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
DEMO1 *node = (DEMO1 *) (malloc(sizeof(DEMO1)));
node->info = data;
node->next = 0;
temp->next = node;
}
}
void printl(DEMO1 * head)
{
DEMO1 *temp;
temp = head;
printf("%d", temp->info);
while (temp != NULL)
{
printf(":) %d\n", temp->info);
temp = temp->next;
}
}
When head is NULL, head is changed within the insertatlast() function only and not in main(). return head to update head in main() also.
DEMO1* insertatlast(DEMO1 * head, int data)
{
if (head == NULL)
{
DEMO1 *node = (DEMO1 *) (malloc(sizeof(DEMO1)));
node->info = data;
node->next = 0;
head = node;
}
else
{
DEMO1 *temp;
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
DEMO1 *node = (DEMO1 *) (malloc(sizeof(DEMO1)));
node->info = data;
node->next = 0;
temp->next = node;
}
return head;
}
int main()
{
int temp;
DEMO1 *head = NULL;
if (head == NULL)
while (1)
{
printf("ENTER 0 to exit");
scanf("%d", &temp);
if (temp == 0)
break;
head=insertatlast(head, temp);
}
printl(head);
return 0;
}
When you compile it (after fixing the missing <> in #includes, you can read some warning from your compiler — hopefully you have warnings enabled. Even if they doesn't solve your problem, it is a good habit to take a look at them.
Lines like
DEMO1 *head = NULL;
if (head == NULL)
should suggest you you are doing something wrong. The fact the if-body is executed, tell you alone that head is NULL when you call insertatlast. That's fine, you expect it. What you likely do not expect is that your head is not modified by the call to insertatlast: so when you call printl, head is NULL still, and calling
`printl(NULL);`
is problematic, because of
temp = head;
... temp->info ...
I guess someone told you that if you want to modify a value of a variable in the caller, you have to pass a pointer to that variable, and that since you have already a pointer, you get confused.
The fact is, a pointer is a variable too, and if you need to modify it, you must get the pointer to... a pointer.
DEMO1* head = NULL;
//...
insertatlast(&head, temp);
and your prototype for the insert would be
void insertatlast(DEMO1 **head, int data);
Then, you modify the caller variable (the DEMO1*), access it and so on, by using *head (don't forget that in insertatlast head has type DEMO1**, and so *head has type DEMO1*).
Note
Do not cast malloc return value; in C
DEMO1* node = malloc(sizeof (DEMO1));
suffices.

Resources