Search code examples
clinked-list

Linked List in order


So we have been given an array of numbers and we are required to print them out in order using linked lists

Array: 19 2 3 13 124 6521 23 1 451 5 3123 412 354 13 13 23 13 1 45

But i dont get why but my code keeps printing out 45

I think ive done it correctly but heres my code either way

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

typedef struct node_s node_t;
struct node_s
{
    int n;
    struct node_s *next;
};

node_t *new_element()
{
    node_t *new;
    new= malloc(sizeof(node_t));
    if(new==NULL)
    {
        printf("Error");
        exit(1);
    }
    return new;
}

node_t *list(node_t *head)
{
    FILE *file;
    file= fopen("file","r");
    if(file==NULL)
    {
        exit(1);
    }
    int n;
    node_t *new=NULL;
    node_t *p=NULL;
    new= new_element();
    while (fscanf(file,"%d", &n)!=EOF)
    {
        new->n=n;
        new->next=NULL;
        if(head==NULL)
        {
            head=new;
        }
        else
        {
            p=head;
            while (p->next!=NULL && p->next->n<new->n)
            {
                p=p->next;
            }
            new->next=p->next;
            p->next=new;
        }
    }
    return head;
}

void printList(node_t *head)
{
    node_t *new=head;
    while(new != NULL)
    {
        printf("%d-->",new->n);
        new=new->next;
    }
    printf("NULL");
    return;
}
int main() {

    node_t *head=NULL;
    head= list(head);
    printList(head);
    return 0;
}

Basically what i tried to do is. We create a new node with the acquired number. Firstly we check if list is empty or not. If it is we put the new node as the head.

Else we check the numbers, so if the number of the next node is lower than the number of the new node we change the pointers. The next pointer of new points to the next node of the link and the pointer that pointed to the next node now points to the new node.

At least i tried to implement what i said.


Solution

  • Ok nevermind i found a problem. When i did the new=new_element(); i had to put that in the while loop.