I have to generate random numbers and put them in a linked list sorted. my code runs fine on my home computer on cygwin, however when I run it on the schools system, i keep getting that the list is empty. Not sure what the issue is.
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int num;
struct node *next;
}node_t;
node_t* insertNodeSorted(node_t *head, int x);
void printList(node_t *head);
void deleteList(node_t *head);
int main(int argc, char *argv[])
{
node_t *dummy;
int counter = 1;
int a;
if(argc != 4)
{
printf("Error. Exiting program...");
exit(1);
}//end if
//seed random number
srandom(atoi(argv[1]));
dummy = NULL;
while(counter < atoi(argv[2]))
{
a = random() % (atoi(argv[3]) + 1);
printf("%d " ,a);
insertNodeSorted(dummy, a);
counter++;
}//end while
printf("
");
printList(dummy);
deleteList(dummy);
return 0;
}
node_t* insertNodeSorted(node_t *head, int x)
{
if(head == NULL)
{
head = (node_t *)malloc(sizeof(node_t));
if(head == NULL)
{
printf("Failed to create head node");
return head;
}//end if
head->num = x;
head->next = NULL;
return head;
}//end if
node_t *p;
p = (node_t*)malloc(sizeof(node_t));
if(p == NULL)
{
printf("Failed to create a new node.");
return p;
}//end if
p->num = x;
p->next = NULL;
if(x < head->num)
{
p->next = head;
return p;
}//end if
node_t *q, *r;
q = head;
while(q != NULL && q->num <= x)
{
r = q;
q = q->next;
}//end while
p->next = q;
r->next = p;
}
void printList(node_t *head)
{
node_t *p;
if(head == NULL)
{
printf("List is empty");
exit(1);
}//end if
p = head->next;
while(p != NULL)
{
printf("%d ",p->num);
p = p->next;
}//end while
}
void deleteList(node_t *head)
{
node_t *p;
while(p != NULL)
{
p = head->next;
free(head);
head = p;
}//end while
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…