[英]Linked list issue in C
我必須生成隨機數,然后將它們放在排序的鏈表中。 我的代碼可以在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("\n\n");
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的虛擬對象發生了什么,以及insertNodeSorted內部head的局部值。
如果您只是使用gcc而沒有調試器...添加更多printfs會幫助很多...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.