Reputation: 79
When i try to delete the 2th node of the list i got the first element equal to zero and the the 2th node not changed im using code blocks version 13.12..............................................................
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* Insert(struct node* head , int x)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(head == NULL) {
temp->data = x;
temp->next = NULL;
head = temp;
return head; }
temp->data = x;
temp->next = NULL;
struct node* temp1;
temp1 = head;
while(temp1->next != NULL) {
temp1= temp1->next;
}
temp1->next = temp;
return head;
}
struct node* Delete (struct node* head, int a)
{
struct node* temp1 = head;
if (a == 1)
head = temp1->next;
free (temp1);
return head;
for(int i = 0; i < a-2; i++)
temp1 = temp1->next;
struct node* temp2;
temp2 = temp1->next;
temp1->next = temp2->next;
free (temp2);
return head;
}
void print(struct node* head)
{
while(head != NULL)
{
printf("the data is %d \n", head->data);
head = head->next;
}
}
int main ()
{
struct node* root = NULL;
int a,c;
printf("How many numbers ? : \n");
scanf("%d",&a);
for(int i = 0; i<a; i++)
{
printf("Enter a number:\n");
scanf("%d",&c);
root = Insert(root, c);
}
Delete(root, 2);
print(root);
return 0;
}
Upvotes: 1
Views: 43
Reputation: 34585
I found two mistakes in your code. The first is not bracing a code block in function Delete
if (a == 1)
head = temp1->next;
free (temp1);
return head;
Without braces, free (temp1); return head;
will always execute. It should be
if (a == 1) {
head = temp1->next;
free (temp1);
return head;
}
The second mistake is not assigning the return value from Delete
to root
. It should be
root = Delete(root, 2);
After correcting these, it seems to run properly.
Upvotes: 2