s1k3s
s1k3s

Reputation: 71

Simple linked list with random values

Okay so here's the task: Implement a list with 25 ordered random integers between 0 and 100.

My approach: get 25 numbers in an array, order the array and create the list with the array elements.

#include <conio.h>
#include <malloc.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

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

int main()
{
    struct Node *p=NULL;
    struct Node *q=NULL;
    int j,i,aux,n,v[25];

    for (i=0;i<25;i++)
    {
        v[i]=rand()%100;
    }

    for (i=0;i<25;i++)
    {
        for (j=1;j<25;j++)
        {
            if (v[i]>v[j])
            {
                aux=v[i];
                v[i]=v[j];
                v[j]=v[i];
            }
        }
    }

    q=(Node *)malloc(sizeof(struct Node));

    q->data=v[0];
    q->next=NULL;

    for (i=1;i<25;i++)
    {
        p=(Node *)malloc(sizeof(struct Node));
        q->next=p;
        p->data=v[i];
        p->next=NULL;
        q=p;
    }

    while (p)
    {
        printf("%d ",p->data);
        p=p->next;
    }

}

Output: 0.

Can you guys figure out what I did wrong ?

Upvotes: 0

Views: 1342

Answers (2)

wildplasser
wildplasser

Reputation: 44240

You don't need to set up all this array stuff; the fragment below returns a linked list of N=cnt Nodes with random payload:

struct Node *getnrandom(unsigned cnt) {
struct Node *p=NULL, **pp;

for (pp=&p; cnt--; pp = &(*pp)->next) {
    *pp = malloc (sizeof **pp);
    if (!*pp) break;
    (*pp)->data = rand();
    }
if (*pp) (*pp)->next = NULL;
return p;
}

UPDATE: since the OP appears to need the values to be ordered, he could either perform insertion (at the right position) into the llist (N*N) , or sort it post hoc. (NlogN)

Upvotes: 0

Mike
Mike

Reputation: 49383

There's a number of things wrong... but the primary one (that's causing all 0's) is here:

        if (v[i]>v[j])
        {
            aux=v[i];
            v[i]=v[j];
            v[j]=v[i];
        }

Your swap is incorrect, you store v[i]'s data in aux, but you never set it to v[j], so you're just overwriting everything with the smallest value (0)

You wanted:

v[j] = aux;

The other major issue is you're not keeping track of the "head" of your list:

    p=(struct Node *)malloc(sizeof(struct Node));
    q->next=p;
    p->data=v[i];
    p->next=NULL;
    q=p;

You keep assigning a new value to p, then overwritting q with p... so there's no way to find your way back. You'll only have the last value in your linked list

Something like:

struct Node* head = NULL;
...
head = q=(Node *)malloc(sizeof(struct Node)); // head points to the first node now

Then later:

p = head; // reset p to the start of the list.
while (p)
{
    ...

Upvotes: 1

Related Questions