Search code examples
cdata-structuressingly-linked-list

First element disappearing using Linked Lists in C


I am a beginner learning about data structures and Abstract Data Types in C. I am creating a simple linked-list implementation, but when I try to print the list, I seem to lose the first element. The Node type just consists of an integer and a pointer to itself.

My main file

  int main()
  {
     Node * List=createList();

     int testData[] = {1,2,3,4,5,6};

     for (int i = 0 ; i < 6 ; i++)
     {
       addFront(List,testData[i]);
       printList(List);
       printf("\n");
     }

  }

addToFront and its supporting initNode are defined thusly:

 void addFront(Node * List, int value)
 {
    Node * toAdd = initNode(value);

    toAdd-> next = List->next;

    List->next = toAdd;
 }



 Node * initNode(int val)
 {
    Node * newNode = malloc(sizeof(Node));
    newNode -> value = val;
    newNode-> next = NULL;

    return newNode;
 }

EDIT: As per request, printList() is:

  void printList(Node * List)
  {
     Node * original = List->next;

     while (List->next != NULL)
     { 
        printf("%d\n",List->value);
        List = List ->next;
     }

     List = original;
  }

Any ideas of what could be wrong?


Solution

  • Assuming that the first node is not used for data but only to point to the rest of the list, most of your code looks ok. The problem is that you're not printing all the nodes in your list.

    Inside printList(), you don't need original since List from the function arguments is local anyway... and you need to break the loop when the node you're looking at is NULL instead of when its next node is NULL (since the while test happens before the loop body).

    Here's a shortened and corrected version, which also updates the List pointer inside the while condition instead of before the loop and in the loop body.

    void printList(Node * List)
    {
       while ((List = List->next) != NULL)
       { 
          printf("%d\n",List->value);
       }
    }