Delete Node - Linked List - C - c

I am trying to delete a node from a linked list but I am still new to the concept of double pointers so I tried using a global variable to hold the head pointer instead. However, I get the wrong results when I try to print my list after deleting the middle node.
I saw this question
deleting a node in the middle of a linked list and I don't know how is my delete node function different from the answer.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char u8;
typedef struct Node node;
void addfirstnode( u8 );
void addnode( u8 );
void print( void );
void deletenode( u8 key );
void deleteonlynode();
void deletefirstnode();
struct Node
{
u8 x;
node *next;
};
node *head;
u8 length = 0;
void main( void )
{
u8 x;
printf( "\nTo add node enter 0\nTo print linked list enter 1\nTo exit press 2\nTo delete node press 3\nYour Choice:" );
scanf( "%d", &x );
if ( x == 2 )
{
printf( "\nThank You\nGood Bye" );
}
while ( x != 2 )
{
switch ( x )
{
u8 n;
u8 key;
case 0: //Add node
printf( "\nPlease enter first value:" );
scanf( "%d", &n );
if ( length == 0 )
{
addfirstnode( n );
//printf("%d",head->x);
}
else
{
addnode( n );
}
printf( "\nNode added , Thank you\n" );
break;
case 1: //Print
print();
break;
case 3: //DeleteNode
printf( "\nPlease enter value to be deleted:" );
scanf( "%d", &key );
deletenode( key );
//deletefirstnode();
break;
default:
printf( "\nInvalid Choice please try again\n" );
}
printf( "\nTo add node enter 0\nTo print linked list enter 1\nTo exit press 2\nTo delete node press 3\nYour Choice:" );
scanf( "%d", &x );
if ( x == 2 )
{
printf( "\nThank You\nGood Bye" );
}
}
//where do I use free();
}
void addfirstnode( u8 n )
{
head = ( node * ) malloc( sizeof( node ) );
head->next = NULL;
head->x = n;
length++;
}
void addnode( u8 n )
{
node *last = head;
while ( ( last->next ) != NULL )
{
last = last->next;
}
last->next = ( node * ) malloc( sizeof( node ) );
( last->next )->next = NULL;
( last->next )->x = n;
length++;
}
void print( void )
{
node *last = head;
u8 count = 1;
printf( "\n---------------------" );
if ( last == NULL )
{
printf( "\nList is empty" );
}
while ( last != NULL )
{
printf( "\nNode Number %d = %d", count, last->x );
last = last->next;
count++;
}
printf( "\n---------------------" );
printf( "\n" );
}
void deletenode( u8 key )
{
node *last = head;
//node*postlast = NULL;
if ( ( last->x == key ) && ( last->next == NULL ) )
{
deleteonlynode();
}
else
{
while ( last != NULL )
{
if ( ( last->x ) == key )
{
printf( "value to be deleted is found" );
node *temp = last->next;
last->next = last->next->next;
free( temp );
length--;
}
last = last->next;
}
}
}
void deleteonlynode()
{
printf( "\n Deleting the only node" );
free( head );
head = NULL;
length--;
}
void deletefirstnode()
{
printf( "\n Deleting the first node" );
node *temp = head;
head = head->next;
free( temp );
length--;
}

The code is removing the wrong item from the linked list:
See:
if ( ( last->x ) == key )
{
printf( "value to be deleted is found" );
node *temp = last->next; // last->next? No, just last.
last->next = last->next->next;
free( temp );
length--;
}
last is pointing at the element to be removed. But then the code assigns temp to point at last->next (NOT last), and then cuts that from the list.
So by looking at node->next rather than the current node, it's possible to trim it out since you're starting from the pointer before the one to remove. Basically your code was almost there already.
void deletenode( u8 key )
{
node *ptr = head;
if ( ( ptr->x == key ) )
{
// Delete the first/head element
node *temp = ptr;
head = head->next;
free( temp );
length--;
}
else
{
while ( ptr->next != NULL )
{
if ( ( ptr->next->x ) == key )
{
printf( "value to be deleted is found" );
node *temp = ptr->next;
ptr->next = ptr->next->next;
free( temp );
length--;
}
ptr = ptr->next;
}
}
}
Also I took the liberty of renaming last to ptr because it was confusing me.
EDIT: Updated to remove the head cleanly too.

Your code seems to be deleting last->next while last should be the node that matches the key.
I guess the following code may be shorter and do the deletion
node* head;
/* returns the node* the previous_node->next should be after the deletion */
node* delete_node(node* current, u8 key) {
if (current == NULL) return NULL; // deletion comes to end
if (head->x == key) {
node* temp = current->next;
free(current);
return delete_node(temp, key);
}
current->next = delete_node(current->next, key);
return current;
}
int main() {
// build the linked list
// ...
head = delete_node(head, key);
return 0;
}
However, this implement (which uses recursion instead of loop) may cause StackOverFlow if the list is too long. I had not tested if gcc would optimize the recursion out.

Related

A C function that inserts number into a linked list in ascending order

This is my function:
void IntListInsertInOrder (IntList L, int v)
{
struct IntListNode *n = newIntListNode (v);
if (L->first == NULL) { //case a, empty list
L->first = L->last = n;
L->size ++;
return;
}
else if (v <= L->first->data) { // case b, smallest value
n->next = L->first;
L->first = n;
}
else if (v >= L->last->data) { // case c, largest value
L->last->next = n;
L->last = n;
}
else if (v > L->first->data && v <= L->first->next->data) { // case d, second-smallest value
n->next = L->first->next;
L->first->next = n;
}
else { //case f, value in the middle
struct IntListNode *curr = L->first;
while (curr->next->data < v) {
curr = curr->next;
}
n->next = curr->next;
curr->next = n;
}
L->size ++;
return;
}
when i put random lists of 10 numbers into it, 3/10 sorted correctly. the errors seem to be in the last part but it looks exactly like solutions i found online.
OK I figured it out. I forgot to add&& curr-> != NULLin the condition of the last while loop. After I added that all the test cases passed.
Your function is too complicated, has many if conditions and as a result it is error-prone and unreadable.
You did not show the list definition but I can guess that you have a two-sided singly-linked list because nowhere in the code there is a reference to a data member named prev.
Here is a demonstrative program that shows how the function can be simply defined.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node
{
int data;
struct Node *next;
} Node;
typedef struct List
{
Node *head;
Node *tail;
size_t size;
} List;
int insert_in_order( List *list, int data )
{
Node *new_node = malloc( sizeof( Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = data;
Node **current = &list->head;
while ( *current != NULL && !( data < ( *current )->data ) )
{
current = &( *current )->next;
}
new_node->next = *current;
if ( *current == NULL )
{
list->tail = new_node;
}
*current = new_node;
++list->size;
}
return success;
}
void clear( List *list )
{
while ( list->head != NULL )
{
Node *current = list->head;
list->head = list->head->next;
free( current );
}
}
void display( const List *list )
{
printf( "There are %zu nodes in the list\n", list->size );
printf( "They are: " );
for ( const Node *current = list->head; current != NULL; current = current->next )
{
printf( "%d -> ", current->data );
}
puts( "null" );
}
int main(void)
{
List list = { .head = NULL, .tail = NULL, .size = 0 };
srand( ( unsigned int )time( NULL ) );
const size_t N = 10;
for ( size_t i = 0; i < N; i++ )
{
insert_in_order( &list, rand() % ( int )N );
}
display( &list );
clear( &list );
return 0;
}
The program output might look like
There are 10 nodes in the list
They are: 1 -> 2 -> 3 -> 3 -> 6 -> 6 -> 7 -> 8 -> 8 -> 9 -> null

loop for insertion in linked list not working

I'm trying to insert some nodes at the end of the linked list but something is not right in this code.
Here I'm trying to make a loop and with the help of this loop I want the user to enter all numbers for the list but I guess I'm missing something.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
void insert(struct node** ref)
{ int n,i=0 ;
printf("how many numers:\n");
scanf("%d",&n);
fflush(stdin);
for(i=0;i<n;i++)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
struct node* last = *ref;
printf("enter the number:\n");
scanf("%d",&(temp->data));
fflush(stdin);
temp->next = NULL;
if(*ref==NULL)
{
*ref = temp;
return;
}
while(last->next != NULL)
last = last->next;
last->next = temp;
}
return;
}
int main()
{
struct node* head=NULL;
insert(&head);
return 0;
}
When the function is called for an empty list then it inserts only one element in the list and exits.
if(*ref==NULL)
{
*ref = temp;
return;
}
Also pay attention to that calling fflush for stdin has undefined behavior.
fflush(stdin);
The function can be defined the following way
size_t insert( struct node **ref )
{
printf( "how many numbers: " );
size_t n = 0;
scanf( "%zu", &n );
if ( n != 0 )
{
while ( *ref != NULL )
{
ref = &( *ref )->next;
}
}
size_t i = 0;
for ( ; i < n && ( *ref = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *ref )->data = 0;
( *ref )->next = NULL;
printf( "enter the number: " );
scanf( "%d", &( *ref )->data );
ref = &( *ref )->next;
}
return i;
}
Here is a demonstrative program
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
size_t insert( struct node **ref )
{
printf( "how many numbers: " );
size_t n = 0;
scanf( "%zu", &n );
if ( n != 0 )
{
while ( *ref != NULL )
{
ref = &( *ref )->next;
}
}
size_t i = 0;
for ( ; i < n && ( *ref = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *ref )->data = 0;
( *ref )->next = NULL;
printf( "enter the number: " );
scanf( "%d", &( *ref )->data );
ref = &( *ref )->next;
}
return i;
}
void display( struct node *head )
{
for ( ; head != NULL; head= head->next )
{
printf( "%d -> ", head->data );
}
puts( "null" );
}
int main(void)
{
struct node *head = NULL;
size_t n = insert( &head );
printf( "There are %zu nodes in the list. They are\n", n );
display( head );
return 0;
}
Its output might look like
how many numbers: 5
enter the number: 1
enter the number: 2
enter the number: 3
enter the number: 4
enter the number: 5
There are 5 nodes in the list. They are
1 -> 2 -> 3 -> 4 -> 5 -> null

merge two sorted linked list into one linked list (recursion)

I had to write a recursive function that receives two sorted lists:
typedef struct listNode {
int* dataPtr;
struct listNode* next;
} ListNode;
typedef struct list
{
ListNode* head;
ListNode* tail;
} List;
and merge them into one sorted list.
I wrote these functions:
void mergeRec(ListNode* head1, ListNode* head2, ListNode* mergedList)
{
if (head1 == NULL && head2 == NULL)
return;
else if (head1 == NULL) {
mergedList->next = head2;
head2 = head2->next;
}
else if (head2 == NULL) {
mergedList->next = head1;
head1 = head1->next;
}
else if (*(head1->dataPtr) > *(head2->dataPtr)) {
mergedList->next = head1;
head1 = head1->next;
}
else
{
mergedList->next = head2;
head2 = head2->next;
}
mergeRec(head1, head2, mergedList->next);
}
List merge(List lst1, List lst2)
{
List mergedList;
makeEmptyList(&mergedList);
mergeRec(lst1.head, lst2.head, mergedList.head);
return mergedList;
}
Now, the problem I have with the recursive function is that at the first call when merged list is pointing to null, so obviously when I write something like mergeList->next I will get a running bug.
I tried to solve it by adding the following condition in the recursion:
if (mergedList == NULL)
{
if (*(head1->dataPtr) > *(head2->dataPtr))
{
mergedList = head1;
head1 = head1->next;
}
else
{
mergedList = head2;
head2 = head2->next;
}
}
but I got this error:
"Exception thrown at 0x00661EB9 in q2d.exe: 0xC0000005: Access violation writing location 0x01000F48."
I can't tell the problem, or how do I solve it.
I would very much appreciate your help.
Thanks!
For starters it is entirely unclear why in this structure there is a data member of type int *
typedef struct listNode {
int* dataPtr;
struct listNode* next;
}List;
instead of just of type int
typedef struct listNode {
int data;
struct listNode* next;
}List;
Nevertheless, the functions merge and mergeRec are invalid because they deal with copies of values of lists and of pointers list1.head, list2.head, and mergedList.head.
List merge(List lst1, List lst2)
mergeRec(lst1.head, lst2.head, mergedList.head);
Moreover the pointers list1.tail, list2.tail, and mergedList.tail are ignored.
I can suggest the following solution shown in the demonstrative program below.
#include <stdio.h>
#include <stdlib.h>
typedef struct listNode
{
int *dataPtr;
struct listNode *next;
} ListNode;
typedef struct list
{
ListNode *head;
ListNode *tail;
} List;
void makeEmpty( List *list )
{
list->head = list->tail = NULL;
}
int push( List *list, int data )
{
ListNode *current = malloc( sizeof( ListNode ) );
int success = current != NULL;
if ( success )
{
current->dataPtr = malloc( sizeof( int ) );
success = current->dataPtr != NULL;
if ( success )
{
*current->dataPtr = data;
current->next = NULL;
if ( list->head == NULL )
{
list->head = list->tail = current;
}
else
{
list->tail = list->tail->next = current;
}
}
else
{
free( current );
current = NULL;
}
}
return success;
}
List merge( List *first, List *second )
{
List result;
makeEmpty( &result );
if ( ( second->head != NULL ) &&
( first->head == NULL || *second->head->dataPtr < *first->head->dataPtr ) )
{
result.head = result.tail = second->head;
second->head = second->head->next;
if ( second->head == NULL ) second->tail = NULL;
}
else if ( first->head != NULL )
{
result.head = result.tail = first->head;
first->head = first->head->next;
if ( first->head == NULL ) first->tail = NULL;
}
if ( !( first->head == NULL && second->head == NULL ) )
{
List tmp = merge( first, second );
result.head->next = tmp.head;
result.tail = tmp.tail;
}
return result;
}
void output( const List *list )
{
for ( const ListNode *current = list->head; current != NULL; current = current->next )
{
printf( "%d ", *current->dataPtr );
}
puts( "NULL" );
}
int main(void)
{
List even_numbers;
List odd_numbers;
makeEmpty( &even_numbers );
makeEmpty( &odd_numbers );
const int N = 10;
for ( int i = 0; i < N; i++ )
{
i % 2 == 0 ? push( &even_numbers, i )
: push( &odd_numbers, i );
}
printf( "even_numbers: " ); output( &even_numbers );
printf( "odd_numbers: " ); output( &odd_numbers );
List all_numbers = merge( &even_numbers, &odd_numbers );
printf( "all_numbers: " ); output( &all_numbers );
printf( "even_numbers: " ); output( &even_numbers );
printf( "odd_numbers: " ); output( &odd_numbers );
return 0;
}
The program output is
even_numbers: 0 2 4 6 8 NULL
odd_numbers: 1 3 5 7 9 NULL
all_numbers: 0 1 2 3 4 5 6 7 8 9 NULL
even_numbers: NULL
odd_numbers: NULL

How to find a seg-fault in a pointer to pointer linked list function?

I am creating three functions that enable me to insert into a linked list using pointer to pointer format in different ways. The problem is I am getting a seg fault in one of these functions and gdb is not telling me where they are for some reason. Any suggestions on where they might be?
// This is the function where I can insert to the front:
void insertAtHead( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
n->value = val;
n->next = *link;
list->length++;
}
//This is the function where I can insert at the end.
void insertAtTail( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
Node *temp;
n->value = val; // Link the data part
n->next = NULL;
temp = *link;
while(temp->next != NULL)
temp = temp->next;
temp->next = n; // Link address part
list->length++;
}
//This function lets me insert the value by finding the largest value and putting the given value before it.
void insertSorted( List *list, int val )
{
Node **link = &( list->head );
Node *n = (Node *)malloc(sizeof(Node));
Node *temp;
n->value = val; // Link the data part
n->next = NULL;
temp = *link;
while(temp->next != NULL || val < temp->value)
temp = temp->next;
temp->next = n; // Link address part
list->length++;
}
// Lastly, the main function:
int main( int argc, char *argv[] )
{
FILE *fp;
if ( argc != 2 || ( fp = fopen( argv[ 1 ], "r" ) ) == NULL ) {
printf( "Can't open file: %s\n", argv[ 1 ] );
exit( EXIT_FAILURE );
}
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertAtHead( &list, val );
printList( &list );
freeList( &list );
}
fseek( fp, SEEK_SET, 0 );
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertAtTail( &list, val );
printList( &list );
freeList( &list );
}
fseek( fp, SEEK_SET, 0 );
{
List list = { NULL, 0 };
int val;
while ( fscanf( fp, "%d", &val ) == 1 )
insertSorted( &list, val );
printList( &list );
freeList( &list );
}
fclose( fp );
return EXIT_SUCCESS;
}
The main function and the rest of the small function I know are correct but the problem seems to be from one of those three functions. I appreciate any help!

how to connect a struct nodes(linked lists)?

i want to make a new node that is a copy of Node_1 connected to Node_2
, the problem is that i need to choose elemenets in each node that
accept a specific condition thhat i insert in the connection function
. for example if i have two nodes that i want to connect to each other
(the second one at the end of the first one) , but i want to chose the
elements in each node that are for example odd ! (for example : first
linked list has the following elements(1 2 3 ) , and the second linked
list has the following elements (4 5 6) then i want to have a new linked list >that has the following elements : (1 3 5)
now my main problem is that i need to work with pointers to
functions because each time i want to give the function different
conditions .
i wrote this function with the assumption that i have a
ConditionFunction, but actually i an kinda stuck on how to make a
ConditionFunction in the main function that can actually do what i
want :/ (for example linke only the odd numbers)
i wrote this function to connect the two linked lists :
// the struct:
typedef struct node_t* Node;
struct node_t {
Element element;
Node next;
};
// ConditionNode a pointer to a function that has condition
// CopyNode a pointer to a function that copy's the node
Node concatLists(Node Node_1,Node Node_2,ConditionNode ConditionFunction,CopyNode copyFunction,void* condition){
Node currentNode=NULL;
Node* New_Node=NULL;
Node head=NULL;
while(Node_1!=NULL){
if(ConditionFunction(Node_1->element,condition)==0){
Node_Result=create_node(&New_Node);
if(head==NULL){
head=New_Node;
currentNode=New_Node;
}
currentNode->next=New_Node;
currentNode=New_Node;
Node_1=GetNextNode(Node_1);
}
else{
Node_1=GetNextNode(Node_1);
}
}
while(Node_2!=NULL){
if(CmpFunction(Node_2->element,condition)!=0){
if(head==NULL){
head=New_Node;
currentNode=New_Node;
}
currentNode->next=New_Node;
currentNode=New_Node;
Node_2=GetNextNode(Node_2);
} else {
Node_1=GetNextNode(Node_1);
}
}
return head;
}
Node_Result create_node(Node* CreatedNode) {
Node newNode = malloc(sizeof(*newNode));
if(!newNode) {
return MEM_PROBLEM;
}
newNode->element =0;
newNode->next = NULL;
*CreatedNode=newNode;
return NODE_SUCCESS;
}
Node GetNextNode(Node node){
if(node==NULL){
return NULL;
}
return node->next;
}
i wrote an example but i think it is wrong :\
int main(){
int array_1[3]={1,2,3};
int array_2[4]={4,5,6,7};
Node head_1=createAllNode(array_1,3);
Node head_2=createAllNode(array_2,4);
int num=2;
Node oddhead=concatLists(head_1,head_2,&copyInt,&checkIfOdd,&num);
printIntElements(oddhead);
return 0;
}
static Node createAllNode(int* array,int len){
Node head;
Node_Result result=create_node(&head);
if(result!=NODE_SUCCESS){
return NULL;
}
Node new_node=NULL;
int j=0;
while(len){
/*int *num=malloc(sizeof(*num));
if(num==NULL){
return NULL;
} */
int element=array[j];
head->element=*(int *)element;
if(j != len-1){
result=create_node(&new_node);
}
if(Node_Result!=NODE_SUCCESS){
return NULL;
}
head->next=new_node;
head=new_node;
new_node=GetNextNode(new_node);
j++;
len--;
}
return head;
}
static void* copyInt(void* num){
int* newInt=malloc(sizeof(*newInt));
*newInt=*(int*)num;
return newInt;
}
/*
static bool PrimaryIntNode(void*num1,void* num2){
}
*/
static void printIntElements(Node head){
while(head!=NULL){
printf("%d",(int*) head->element);
head=GetNextNode(head);
}
}
static bool checkIfOdd(Element num1,int num2){
int num=*(int *)num1;
if(num<0){
num *=-1;
}
return num % num2 != 0;
}
and i call the coonect list function like this in the main function :
Node oddhead=concatLists(head_1,head_2,&copyNode,&checkifIdd,&num);
can anyone just show me a correct example oh how actually use a
function like this in main !! because i get all kinda of errors in
eclipse ..
I will not use your definitions because they are confusing. I will just demonstrate how two lists can be concatenated by selecting nodes that satisfy some condition. You can use the presented demonstrative program as a base for your own list implementation.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert( struct node **head, const int a[], size_t n )
{
if ( *head != NULL ) head = &( *head )->next;
for ( size_t i = 0; i < n; i++ )
{
struct node *tmp = malloc( sizeof( struct node ) );
tmp->data = a[i];
tmp->next = *head;
*head = tmp;
head = &( *head )->next;
}
}
struct node * concatLists( struct node *head1, struct node *head2, int cmp( struct node * ) )
{
struct node *head = NULL;
struct node **current = &head;
for ( ; head1 != NULL; head1 = head1->next )
{
if ( cmp( head1 ) )
{
*current = malloc( sizeof( struct node ) );
( *current )->data = head1->data;
( *current )->next = NULL;
current = &( *current )->next;
}
}
for ( ; head2 != NULL; head2 = head2->next )
{
if ( cmp( head2 ) )
{
*current = malloc( sizeof( struct node ) );
( *current )->data = head2->data;
( *current )->next = NULL;
current = &( *current )->next;
}
}
return head;
}
void output( struct node *head )
{
for ( ; head != NULL; head= head->next )
{
printf( "%d ", head->data );
}
}
int odd( struct node *n )
{
return n->data % 2;
}
int main( void )
{
struct node *head1 = NULL;
struct node *head2 = NULL;
int a1[] = { 1, 2, 3 };
int a2[] = { 4, 5, 6 };
const size_t N1 = sizeof( a1 ) / sizeof( *a1 );
const size_t N2 = sizeof( a2 ) / sizeof( *a2 );
insert( &head1, a1, N1 );
insert( &head2, a2, N2 );
struct node *head3 = concatLists( head1, head2, odd );
output( head1 );
putchar( '\n' );
output( head2 );
putchar( '\n' );
output( head3 );
putchar( '\n' );
return 0;
}
The program output is
1 2 3
4 5 6
1 3 5

Resources