I am trying to write a program that generate an ordered random linked list.
The problem is that the output sometimes is only 4 numbers and sometimes is an
infinite sequence of numbers. I think the problem is in the gen function, how can i fix it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
struct node{
int v;
struct node *nextPtr;
};
typedef struct node Node;
typedef Node *NodePtr;
void gen(NodePtr *startPtr);
void print(NodePtr start);
int main()
{
NodePtr startPtr;
startPtr = NULL;
gen(&startPtr);
print(startPtr);
return 0;
}
void gen(NodePtr *startPtr)
{
NodePtr currPtr, lastPtr, newPtr;
int r;
lastPtr = NULL;
srand(time(NULL));
for(int i = 0; i < N; i++){
currPtr = *startPtr;
r = rand()%101;
while(currPtr != NULL && r > currPtr->v){
lastPtr = currPtr;
currPtr = currPtr->nextPtr;
}
newPtr = malloc(sizeof(Node));
newPtr->v = r;
newPtr->nextPtr = NULL;
if(lastPtr == NULL){
*startPtr = newPtr;
}
else{
lastPtr->nextPtr = newPtr;
newPtr->nextPtr = currPtr;
}
}
}
void print(NodePtr start)
{
while(start != NULL){
printf("%d ", start->v);
start = start->nextPtr;
}
}