Deleting a node at a given position in Linked List - c

Given a singly linked list and a position, i am trying to delete a linked list node at a specific position.
CODE:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void printList(struct node* head_ref)
{
//struct node* head_ref = (struct node*)malloc(sizeof(struct node));
if(head_ref == NULL)
printf("The list is empty");
while(head_ref!=NULL)
{
printf("%d\n",head_ref->data);
head_ref = head_ref->next;
}
}
void insert_beg(struct node **head_ref,int new_data)
{
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void delete(struct node **head_ref,int position)
{
int i=1;
if(*head_ref == NULL)
return;
struct node *tails,*temp = *head_ref;
if(position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
while(temp->next!=NULL)
{
tails = temp->next;
temp = temp->next;
if(i == position)
{
tails->next = temp->next;
free(temp);
return;
}
i++;
}
}
int main()
{
struct node *head = NULL;
insert_beg(&head,36);
insert_beg(&head,35);
insert_beg(&head,34);
insert_beg(&head,33);
printList(head);
int position;
printf("Enter the position of the node u wanna delete\n");
scanf("%d",&position);
delete(&head,position);
printf("\n");
printList(head);
}
Whenever I am trying to delete a node above position 0, I am getting 0 in that specific position instead of nothing. Could I know where I am going wrong?
For eg my list is : 33 34 35 36
My Output: 33 0 35 36 (while attempting to delete node 1)
Valid Output: 33 35 36

The problem occurs due to this wrong statement
while(temp->next!=NULL)
{
tails = temp->next;
^^^^^^^^^^^^^^^^^^^
temp = temp->next;
In this case tails and temp are the same nodes. And if temp is deleted then you set the data member next of the deleted node to temp->next
if(i == position)
{
tails->next = temp->next;
^^^^^^^^^^^^^^^^^^^^^^^^^
Here tails is node that will be deleted.
You should change the data member next of the node before the deleted node. So the wrong statement should be updated like
while(temp->next!=NULL)
{
tails = temp;
^^^^^^^^^^^^^
temp = temp->next;
As for me then I would write the function the following way
int delete( struct node **head, size_t position )
{
struct node *prev = NULL;
size_t i = 0;
while ( i != position && *head != NULL )
{
prev = *head;
head = &( *head )->next;
++i;
}
int success = *head != NULL;
if ( success )
{
struct node *tmp = *head;
if ( prev == NULL )
{
*head = ( *head )->next;
}
else
{
prev->next = ( *head )->next;
}
free( tmp );
}
return success;
}

Into your delete function while loop tails and temp move forward a the same time starting fro the same address. The node is not deleted because you are always assigning the same value (in other words you are only confirm next pointer value each time).
That means that, after your cancellation, printout is UB due to the freed memory of one of the nodes.
Correcting your code:
void delete(struct node **head_ref,int position)
{
int i=1;
if(*head_ref == NULL)
return;
struct node *temp = *head_ref;
if(position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
struct node *tails = *head_ref;
while(temp->next!=NULL)
{
temp = temp->next;
if(i == position)
{
tails->next = temp->next;
free(temp);
return;
}
tails = tails->next;
i++;
}
}

Related

What is the logical error in my attempt to implement the insertion of nodes in the linked list?

I'm unable to get an output for inserting nodes at the beginning, end, and after a given node. I'm not very sure if there is anything that I missed out in the main(). I'm unable to point out my logical error in the program
`
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
//Inserts at the begining
void push(struct node **head, int x){
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->data = x;
*head = newnode;
newnode->next = (*head);
*head = newnode;
}
//Insert at the last
void append(struct node **head, int x){
struct node *temp;
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->next = 0;
if(*head == 0){
*head = newnode;
}
temp = *head;
while(temp->next != 0){
temp = temp->next;
}
temp->next = newnode;
}
//inserting at a given node
void insertAfter(struct node* temp, int x){
if(temp == NULL){
printf("previous node cannot be NULL");
}
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->next = temp->next;
temp->next = newnode;
}
void printList(struct node *temp){
while(temp->next != NULL){
printf("%d",temp->data);
}
temp = temp->next;
}
int main(){
struct node *head = NULL;
append(&head,6);
push(&head, 7);
push(&head, 1);
append(&head, 4);
insertAfter(head->next, 8);
printf("Created linked list is:\n");
printList(head);
return 0;
}
`
The output is 1 7 8 6 4
But I'm getting no output and no errors as well
Within the function print_list there can be an infinite loop because this statement
temp = temp->next;
is placed after the while loop
void printList(struct node *temp){
while(temp->next != NULL){
printf("%d",temp->data);
}
temp = temp->next;
}
The function can look for example the following way
void printList( const struct node *head )
{
for ( ; head != NULL; head = head->next )
printf( "%d -> ", head->data );
}
puts( "null" );
}
Pay attention to that within the function push this statement
*head = newnode;
is present twice.
Also the functions are unsafe because there is no check whether memory was allocated successfully within the functions.
For example the function append could be declared and defined the following way
//Insert at the last
int append( struct node **head, int x )
{
struct node *newnode = malloc( sizeof( *newnode ) );
int success = newnode != NULL;
if ( success )
{
newnode->data = x;
newnode->next = NULL;
while ( *head != NULL ) head = &( *head )->next;
*head = newnode;
}
return success;
}

Element deletion in single linked list at head not working

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
struct node *second = NULL;
struct node *third = NULL;
void insertAtBeg(struct node *n, int data) {
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = head;
head = temp;
}
void insertAtEnd(struct node *n, int data) {
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
temp->next = NULL;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
}
void deleteElement(struct node *head, int data) {
if (head->data == data) {
struct node *temp;
temp = head;
head = head->next;
free(temp);
printf("after deletion at head in function\n");
printList(head);
}
}
void printList(struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
void main() {
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
insertAtBeg(head, 0);
printf("after insertion at beginning\n");
printList(head);
insertAtEnd(head, 4);
printf("after insertion at End\n");
printList(head);
deleteElement(head, 0);
printf("after deletion at head in main\n");
printList(head);
}
output of the code is
1
2
3
after insertion at beginning
0
1
2
3
after insertion at End
0
1
2
3
4
after deletion at head in function
1
2
3
4
after deletion at head in main
0
1
2
3
4
Why is there a difference in output of the function called in main and the function called in another function.ie.after deletion at head in function and after deletion at head in main, when both are supposed to be deleting element from the same list
The problem is you need a way to modify the head of the list when inserting and/or deleting elements from the list.
A simple way to do this is for these functions to return a potentially updated value of the head pointer and for the caller to store this return value into it's head variable.
Here is a modified version of your code with these semantics:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *insertAtBeg(struct node *head, int data) {
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
// should test for memory allocation failure
temp->data = data;
temp->next = head;
return temp;
}
struct node *insertAtEnd(struct node *head, int data) {
struct node *temp;
struct node *n;
temp = (struct node*)malloc(sizeof(struct node));
// should test for memory allocation failure
temp->data = data;
temp->next = NULL;
if (head == NULL)
return temp;
n = head;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
return head;
}
struct node *deleteElement(struct node *head, int data) {
// delete the first node with a given data
if (head->data == data) {
struct node *temp = head;
head = head->next;
free(temp);
} else {
struct node *n = head;
while (n->next != NULL) {
if (n->next->data == data) {
struct node *temp = n->next;
n->next = temp->next;
free(temp);
break;
}
}
}
return head;
}
void printList(const struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
int main() {
struct node *head = NULL;
head = insertAtBeg(head, 1);
head = insertAtEnd(head, 2);
head = insertAtEnd(head, 3);
printList(head);
head = insertAtBeg(head, 0);
printf("after insertion at beginning\n");
printList(head);
head = insertAtEnd(head, 4);
printf("after insertion at End\n");
printList(head);
head = deleteElement(head, 0);
printf("after deletion at head in main\n");
printList(head);
// should free the list
return 0;
}
An alternative is to pass the address of the list head pointer so the function can modify it if needed.
Here is a modified version of your code with this alternative approach:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
struct node *insertAtBeg(struct node **headp, int data) {
struct node *temp = malloc(sizeof(*temp));
if (temp != NULL) {
temp->data = data;
temp->next = *headp;
*headp = temp;
}
return temp;
}
struct node *insertAtEnd(struct node **headp, int data) {
struct node *temp = malloc(sizeof(*temp));
if (temp != NULL) {
temp->data = data;
temp->next = NULL;
if (*headp == NULL) {
*headp = temp;
} else {
struct node *n = *headp;
while (n->next != NULL) {
n = n->next;
}
n->next = temp;
}
}
return temp;
}
int deleteElement(struct node **headp, int data) {
// delete the first node with a given data
struct node *head = *headp;
if (head->data == data) {
*headp = head->next;
free(temp);
return 1; // node was found and freed
} else {
struct node *n = head;
while (n->next != NULL) {
if (n->next->data == data) {
struct node *temp = n->next;
n->next = temp->next;
free(temp);
return 1; // node was found and freed
}
}
return 0; // node not found
}
}
void printList(const struct node *n) {
while (n != NULL) {
printf("%d\n", n->data);
n = n->next;
}
}
int main() {
struct node *head = NULL;
insertAtBeg(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
printList(head);
insertAtBeg(&head, 0);
printf("after insertion at beginning\n");
printList(head);
insertAtEnd(&head, 4);
printf("after insertion at End\n");
printList(head);
deleteElement(&head, 0);
printf("after deletion at head in main\n");
printList(head);
// free the list
while (head != NULL) {
deleteElement(&head, head->data);
}
return 0;
}
This alternative approach uses double pointers, so it is a bit more difficult for beginners to comprehend, but it has a strong advantage: the functions can update the list pointer and provide a meaningful return value that can be tested to detect errors. For example insertAtBeg() and insertAtEnd() return NULL if the new node could not be allocated but preserve the list. Similarly deleteElement() can return an indicator showing whether the element was found or not.
With this approach, you can write functions to pop the first or last element of the list, or the one at a given index, or one with a given data, while updating the list pointer as needed.
In the function void deleteElement(struct node *head,int data) you are passing a pointer to the head node. If you make changes to the node, then that works because you are pointing to the actual node. However, the variable head is a local copy of the pointer, which is not the one in main. When you change head to head->next that is only changing the local copy, so it has no effect outside deleteElement.
ADVANCED LEVEL POINTERS
To actually change head you have to pass a pointer to it, making a double pointer:
void deleteElement(struct node **phead,int data) {
struct node *temp;
temp = *phead;
*phead = (*phead)->next;
this means you have to pass the address of head &head as the parameter.

insert element at nth position in the linked list - C

my program shows list is empty. I think I'm making mistake on re-linking the nodes to the head. Help me figure it out.
void insert(struct node** headRef, int index, int Data)
{
int i, distanceFromHead = 1;
struct node* head = *headRef;
struct node* temp1 = (struct node*)malloc(sizeof(struct node)); //node to be inserted.
temp1->data = Data;
if(index == 0)
{
temp1->next = head;
head = temp1;
return;
}
while(head != NULL)
{
if(distanceFromHead == index)
{
temp1->next = head->next;
head->next = temp1;
*headRef = head;
return;
}
head = head->next;
distanceFromHead++;
}
}
Your have two conditions:
finding the postion for insertion in the Linked list
not falling off the end of the Linked List
And, of course, you have to assign to *headRef, not to some local pointer variable. And you should not call malloc before you are absolutely sure you really need the memory.
You can combine the two conditions in a single loop:
void insert1(struct node **headRef, int index, int Data)
{
struct node *temp1;
int distanceFromHead = 0;
for( ; *head; head = &(*head)->next) {
if(distanceFromHead == index) break;
distanceFromHead++;
}
if (distanceFromHead != index) return; // index not found: list too short
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
}
You dont need the distanceFromHeadvarable; you could just as well decrement the index:
void insert2(struct node **headRef, int index, int Data)
{
struct node *temp1;
for( ; *head; head = &(*head)->next) {
if(!index) break;
index--;
}
if (index) return; // index not found: list too short
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
}
Now, the test for index!=0 is repeated after the loop. This can be avoided by moving the insertion inside the loop, and jumping out afterwards:
void insert3(struct node **headRef, int index, int Data)
{
for( ; *head; head = &(*head)->next) {
struct node *temp1;
if(index--) continue;
temp1 = malloc(sizeof *temp1); //node to be inserted.
temp1->data = Data;
temp1->next = *head;
*head = temp1;
break; // or : return;
}
return;
}
You're using head to iterate through the linked list and if index matched with distance then updating headref.
Problem is *headRef = head in while..if
And in if(index == 0) assign temp1 to *headref i.e. *headref=temp1

Deleting front node from a Singly Linked List in C

I am trying to delete from a Singly Linked List, however, when I try to delete from the first element, it prints garbage. I think the problem comes from the delete_node function, however, I tried everything and I cannot figure it out.
#include <stdio.h>//prinf
#include <stdlib.h>//alloc mallco callo
typedef struct node node;
struct node{
int number;
node *next;
};
node *new_node(int num){
node *n= (node*) malloc(sizeof(node));
n->number=num;
n->next=NULL;
return n;
}
void node_free_all(node *n){
if(n != NULL){
node_free_all(n->next);
free(n);
}
}
void print_nodes(node *n){
if(n != NULL){
print_nodes(n->next);
printf("Number is: %d\n",n->number);
}
}
void delete_node(node *n, int num){
node *rmNode= (node*)malloc(sizeof(node));
//delete first
if( n!= NULL && n->number==num){
rmNode = n;
n=n->next;
free(rmNode);
}
//all but first
while(n != NULL){
if(n->next != NULL && n->next->number == num){
rmNode= n->next;
n->next = rmNode->next;
free(rmNode);
break;
}
n=n->next;
}
}
int main(){
int i;
node *head= (node*) malloc(sizeof(node));
node *curr;
head=NULL;
for(i=1;i<=10;i++) {
curr = new_node(i);
curr->next =head;
head=curr;
}
printf("Everything:\n");
print_nodes(head);
printf("Deleting 1:\n");
delete_node(head,1);
print_nodes(head);
printf("Deleting 5:\n");
delete_node(head,5);
print_nodes(head);
printf("Deleting 2:\n");
delete_node(head,2);
print_nodes(head);
printf("Deleting 3:\n");
delete_node(head,3);
print_nodes(head);
printf("Deleting 10:\n");
delete_node(head,10);
print_nodes(head);
printf("Deleting 9:\n");
delete_node(head,9);
print_nodes(head);
node_free_all(head);
// node_free_all(list);
return 0;
}
What am I doing wrong?
You don't need to allocate memory to rmNode. Plus you need to pass the reference of head pointer to the function delete_node because every time you are updating the list and if you have to delete first element of list, then in this case head pointer also got updated.
struct node
{
int number;
node *next;
};
void delete_node(struct node** head_ref, int num)
{
struct node* temp;
struct node* current = (*head_ref);
//delete first
if( current != NULL && current->number == num)
{
temp = current;
current = current->next;
free(temp);
(*head_ref) = current;
}
else
{
//all but first
while(current != NULL)
{
if(current->next != NULL && current->next->number == num)
{
temp = current->next;
current->next = temp->next;
free(temp);
break;
}
current = current->next;
}
}
}
here's a version that removes all items that matches num, and always update the head item.
void delete_node(node** head_ref, int num)
{
node* temp;
node* last = 0;
node* current = *head_ref;
while(current)
{
if( current->number == num )
{
temp = current;
if( current == *head_ref )
current = (*head_ref) = current->next;
else
current = last->next = current->next;
free(temp);
} else {
last = current;
current = current->next;
}
}
}
You have to call it like delete_node(&head,1);
because it needs an address to the head item to be able to change it

Insert an element in end of a singly Linked List

I have been trying to fix this code since morning but could get it done. So, finally i need some help in figuring out the error. The code compiles with no error but when i run it from terminal i get an error saying "segmetation error: 11"
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *head;
void Insert(int data);
void Print();
int main()
{
head = NULL; //list is empty
Insert(3);
Insert(5);
Insert(2);
Insert(8);
Print();
return 0;
}
void Insert(int data)
{
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node *temp1 = head;
while(temp1 != NULL)
{
temp1= temp1->next;
}
temp1->next = temp;
}
void Print()
{
struct Node *temp =head;
while(temp != NULL)
{
temp = temp->next;
printf("%d", temp->data);
}
}
You never set head to anything other than NULL.
(Even if you fix the above) temp1 is guaranteed to be NULL by the time you get to temp1->next = temp;.
P.S. I don't think it's such a great practice to call you variables temp, temp1 etc. From those names it is impossible to tell what their supposed function is.
Usually single linked lists have an inserting operation that inserts data at the beginning of the list. Nevertheless your function insert can look the following way
void Insert( int data )
{
struct Node *temp = malloc(sizeof( struct Node ) );
temp->data = data;
temp->next = NULL;
if ( head == NULL )
{
head = temp;
}
else
{
struct Node *current = head;
while ( current->next != NULL ) current = current->next;
current->next = temp;
}
}
It would be better if you check in the function whether the node was allocated.
Function Print also is wrong. It can look like
void Print( void )
{
for ( struct Node *current = head; current != NULL; current = current->next )
{
printf( "%d ", current->data );
}
}
You are writing
while(temp1 != NULL)
Make it like this
while(temp1->next != NULL)
Here, temp1 points to null at the end of loop, and you are trying to add node after null i.e.
null->next =temp;
which must be throwing error.
struct Node *curr;
void Insert(int data){
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next =NULL;
if(head == NULL)
curr = head = temp;
else
curr = curr->next = temp;
}
void Print(){
struct Node *temp =head;
while(temp != NULL){
printf("%d ", temp->data);
temp=temp->next;
}
}

Resources