我必须生成随机数,并将它们放入排序的链表中。我的代码在cygwin上的家用电脑上运行得很好,但当我在学校系统上运行它时,我总是发现列表是空的。不确定问题出在哪里。
#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("nn");
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
}
您的函数
- 具有未定义的行为,因为在某些情况下,它不返回任何内容,并且
- 总的来说,您没有重新分配头
dummy
。所以它不是已更改
的功能如下
node_t* insertNodeSorted( node_t **head, int x )
{
node_t *p = ( node_t * )malloc( sizeof( node_t ) );
if ( p == NULL )
{
printf( "Failed to create a new node.n" );
}//end if
else
{
p->num = x;
if ( *head == NULL || x < ( *head )->num )
{
p->next = *head;
*head = p;
}
else
{
node_t *current = *head;
while ( current->next != NULL && !( x < current->next->num ) )
{
current = current->next;
}
p->next = current->next;
current->next = p;
}
}
return p;
}
该函数必须像一样调用
insertNodeSorted( &dummy, a );
既然是家庭作业,我不会给你完整的答案。。。。但是看看main的dummy发生了什么,以及insertNodeSorted中head的本地值。
如果您只是使用gcc而没有调试器。。。添加更多的printf会有很大帮助。。。