Home > Mobile >  Linked list in c returns negative number instead of adding node
Linked list in c returns negative number instead of adding node

Time:12-05

Can someone explain to me why this code returns a random negative number instead of adding the node as it should? If the call to addnode is removed the main function works as it should so the problem lies with the addnode function. I don't think it's malloc that has the problem and I can't for the life of me figure out what is. Please help, I'm an amateur at c and I have a vague understanding of how pointers work so I guess something's wrong with my pointers. Here's the full code :

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int addNode(struct node **head, int value);
void printList(struct node **head);

int main()
{
    int value;
    
    struct node *head;
    head=NULL;
    //int isempty(struct node *head);
    for(int i=0;i<10;i  )
    {
    printf("\nInsert node value :");
    scanf("%d",&value);
    addNode(&head,value);
    }
    printList(&head);
     return 0;
}
int addNode(struct node **head,int value)
    {
    struct node *newnode;
    newnode=(struct node *) malloc(sizeof(struct node));
    //if(newnode==NULL)
    if(!newnode)
    {
    printf("Memory allocation error \n"); 
    exit(0);
    }
    
    if(*head=NULL)
    {
        newnode->data=value;
        newnode->next=NULL;
        *head=newnode;
        return 1;
    }
    else
    {
        
        struct node *current;
        *current = **head;
        while(current != NULL)
        {
            if(value<=(current->data)){
                //περίπτωση 1ου κόμβου σε μη κενή λίστα
                if(current==*head){
                    newnode->data=value;
                    newnode->next=*head;
                    *head=newnode;
                    return 1;
                }
                //περίπτωση ενδιάμεσου κόμβου
                newnode->data=value;
                return 1;
            }
            current = current->next;
        }

    }
}
/*int isempty(struct node *head){
    return (head==NULL);
}*/

void printList(struct node **head) {
   struct node *ptr = *head;
   printf("\n[ ");
    
   //start from the beginning
   while(ptr != NULL) {
      printf("(%d) ",ptr->data);
      ptr = ptr->next;
   }
   printf(" ]");
   return;
}

CodePudding user response:

Well for starters you are having an assignment instead of a comparison in addNode

if(*head=NULL) should be if(*head==NULL)

Other than that, I think you are trying to maintain the elements in a sorted manner? But in any case you are manipulating pointers a bit more than you need to.

  • Related