0

I am trying to make a linked list where each node holds a random integer between 1 and 100 and then print the list. But when the list prints it displays each node as having the same value. I don't know whether I made a mistake when creating the list or am not printing it out right.

Here is my main:

int main()
{
    int numberOfElements;                                                   
    node *front = NULL;                                                     

    printf("\nPlease enter the number of elements in the linked list: ");   
    scanf("%d",&numberOfElements);   

    front = LinkedListMaker(numberOfElements);
    printf("The original (unsorted) linked list with %d nodes (elements)\n",numberOfElements);
    printList(front);

    return 0;                                                                 
}

This is my header:

#ifndef LL
#define LL
#include <time.h>

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

typedef struct node
{
    int index;
    int randomNumber;
    struct node *next;

}node;                  

node * LinkedListMaker(int listSize);
void printList(node *nodeHead);

#endif

This is the function that creates the list:

#include "headers.h"

node *LinkedListMaker(int listSize)
{
    int randNumber;
    node *nodeHead = NULL;
    node *tempNode = NULL;
    node *pointer = NULL;

    for(int i = 0; i < listSize; i++)
    {
        tempNode = (node*)malloc(sizeof(node));

        srand(time(NULL));

        tempNode->randomNumber = rand() %100 + 1;
        tempNode->next = NULL;


        if(nodeHead == NULL)
        {
            nodeHead = tempNode;
        }
        else
        {
            pointer = nodeHead;

            while(pointer->next != NULL)
                pointer = pointer->next;

            pointer->next = tempNode;
        }

    }
    return nodeHead;
}

And this function prints the list:

#include "headers.h"

void printList(node *nodeHead)
{
    int counter = 1;
    node *pointer = nodeHead;

    while(pointer != NULL)
    {
        printf("Node: %d:  Value: %d:\n", counter, pointer->randomNumber);
        pointer = pointer->next;
        counter++;

    }
}

Marco Aiello
  • 179
  • 10
  • [Singly Linked List (node only, no wrapper)](https://pastebin.com/5MPLU4wB) or better [Singly Linked List of Integers (example)](https://pastebin.com/R2AewR3A) (adding a `tail` pointer allows insert-at-end in O(1) time) – David C. Rankin Mar 30 '20 at 03:14
  • `srand` should only be called once. Try taking it out of the loop. – kaylum Mar 30 '20 at 03:16
  • As @kaylum says, and move the single call of `srand()` to `main()`. otherwise you are still making multiple calls if you call `LinkedListMaker()` more than once. – David C. Rankin Mar 30 '20 at 03:18

0 Answers0