Balkanick
Balkanick

Reputation: 11

Scan a linked list in c

I've been asked to create a linked list in c. The user should insert the list by adding one digit at a time from the most significant digit to the less significant one. The problem is that when I print the list (not in reverse), after having it scanned (e.g. calling the function with 3 numdigits), it prints it backwards (tail to head and not head to tail). I am typing 3, 2, 1 and it prints 321 instead of 123. I'm really stuck here. Any help?

typedef struct node{ 
int digit;
struct node *next;
}listnode_t;


listnode_t *create_list(int numdigits) 
{
listnode_t *ptr, *head;
ptr = (listnode_t*)malloc(sizeof(listnode_t));
ptr -> next= NULL;
head = ptr;

int i=0;
int userdigit;

do{
    scanf("%d",&userdigit);
    if (userdigit<0 || userdigit>9)
    {
        printf("Give from 0 to 9\n");
    }
    else{
        ptr -> digit = userdigit;
        ptr -> next = (listnode_t*)malloc(sizeof(listnode_t));
        ptr = ptr -> next;

        i+=1;
    }
}while (i<numdigits);

ptr -> next = NULL;

return head;

}   

void print_number(listnode_t *head)
{
if ((head->next) == NULL){

    printf("Empty list\n");
    return;
}

while ((head->next)!= NULL){
    printf("%d", (head->digit));
    head = head -> next;
}

return ;
}

Upvotes: 1

Views: 3127

Answers (1)

Omar Trkzi
Omar Trkzi

Reputation: 311

Well that's exactly what printing a linked list does; printing the list from the head to the tail, e.g if your input is 1,2,3 then :

  • head->digit == 1
  • head->next->digit == 2
  • head->next->next->digit == 3

Still though if you want to reverse the linked list you can do that using a function, as an example :

node* reverse(node* head)
{
    node* prev    = NULL;
    node* current = head;
    node* next;
    while (current != NULL)
    {
        next  = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return head;
}

More info here : https://www.zentut.com/c-tutorial/c-linked-list/#Reverse_linked_list

Upvotes: 1

Related Questions