XDProgrammer
XDProgrammer

Reputation: 861

Why this linked list prints from last input? C linked-list program

So I have this simple linked list program:

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

typedef struct record record;
struct record {
    char name[32]; 
    float score;
};

typedef struct node node;
struct node {
    record data;
    node *next; 
}; 

int main() {
    char data[100];
    char name[32];
    float x;
    node *p, *head;
    int counter = 0;

    head = 0;

    while ((fgets(data, 60, stdin) != NULL) && counter <= 3) {
        p = (node *) malloc (sizeof(node));

        sscanf(data, "%s %f", name, &x);
        strcpy(p->data.name,name);
        p->data.score = x;
        p->next = head;
        head = p;

        counter++;
    }

     printf("-----------------------\n");
     while (p) {
         printf("%s %f\n",p->data.name, p->data.score);
         p = p->next ;
     }

     return 0;
}

And this is the input and output:

 //input
 bob 10
 shiela 5
 john 1
 elisa 10

 //print input
 elisa 10.000000
 john 1.000000
 shiela 5.000000
 bob 10.000000

Why is it that it start printing from last input?

How can i print this starting from the first data i entered?

Upvotes: 2

Views: 97

Answers (1)

paxdiablo
paxdiablo

Reputation: 882726

The reason you're getting the nodes in reverse order is because this code:

p->next = head;
head = p;

inserts node at the beginning of the list, such as:

head -> null
head -> A -> null
head -> B -> A -> null
head -> C -> B -> A -> null

and so on.

Then, when you traverse from head to null, they appear to come out in reverse order but, in actual fact, that's just an side effect of your insertion method.

If you want them inserted in the list in the "correct" order, introduce a tail pointer and code it thus:

p->next = null;      // new node will always be end of list
if (head == NULL)    // special trap for empty list
    head = p;        //     means set up head
else                 // otherwise
    tail->next = p;  //     current tail now points to new node
tail = p;            // make new node the tail for next time

Upvotes: 6

Related Questions