2017-04-23 90 views
1

我一直有这个链表的问题,特别是它似乎像我的头指针没有链接到我的列表的其余部分,我很困惑,为什么它不是。在我通过引用指针插入我的头指针的地方,它没有连接到main中引用的链表。除非该列表在主函数中没有链接在一起,而我错过了一些东西。链接列表的问题列表没有链接到头指针

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


typedef struct node{ 
    int number; 
    struct node * next; 
} Node; 

typedef Node * Nodeptr; 

void printlist (Node * head){ 
    Node * n = head; 

    while(n != NULL){ 
     printf("%d\n",n ->number); 
     n = n ->next; 
    } 

} 
void sumlist (Node * head){ 
    Node * n = head; 
    int sum; 
    while(n != NULL){ 
     sum = n ->number +sum; 
     n = n ->next; 
    } 
    printf("the total of all numbers in this list is %d",sum); 
} 
search(head){ 



} 
int main(){ 
    int i =0; 
Nodeptr head=NULL; 

if((head = malloc(sizeof(Node))) == NULL) 
return 0; 

head->number =rand()%50+50; 
head ->next = malloc(sizeof(Node)); 

int n; 


Nodeptr newnode = NULL; 
for(n=0;n<99;n++) 
{ 

newnode = malloc(sizeof(Nodeptr)); 

newnode->number = rand()%50+50; 
newnode->next =NULL; 
head -> next = newnode; 



} 


printlist(head); 
sumlist(head); 


return 0; 
} 
+0

BTW'int sum;' - >'int sum = 0;' – BLUEPIXY

+0

它与[this]类似(http://stackoverflow.com/q/43564342/971127) – BLUEPIXY

回答

2

的错误是,你作为一个记录头的连接一切

head -> next = newnode; 

您需要使用被更新的指针:

Nodeptr newnode = NULL; 
Nodeptr last = head; 
for(n=0;n<99;n++) 
{ 
    newnode = malloc(sizeof(Nodeptr)); 
    newnode->number = rand()%50+50; 
    newnode->next =NULL; 
    last -> next = newnode; 
    last = last->next; 
} 

你也应该改变这样的:

head ->next = malloc(sizeof(Node)); // otherwise you will lose this element. 

into

head ->next = NULL; 
+0

我似乎正在获取内存泄漏到某处......当我运行该程序时,它会在列表打印中间崩溃。 –

+0

@GuillermoDiazGranados,你可以看到[这里](http://www.tutorialspoint.com/compile_c_online.php?PID=0Bw_CjBb95KQMclBpT2U0WlB6ZFU)它打印正确。该错误不在插入 – granmirupa

+0

啊好的我刚刚运行我的代码,它工作正常,并要求我的朋友运行它,它运行良好。那么好吧。感谢您的帮助! –

0

你在一个循环中执行这些步骤:

newnode = malloc(sizeof(Nodeptr)); 
newnode->number = rand()%50+50; 
newnode->next =NULL; 
head -> next = newnode; 

您设置newnode->旁边指向空,头戴式>旁边指向newnode。

这意味着,每次通过循环你的头都会得到一个新的下一个,就是这样。

实际上,每次通过循环时,都会将先前的新节点放在地板上,然后链接到新的节点。最后,您将头部指向1个节点,并且您将有98个节点落在您无法到达的地板上。你需要保留一个“尾部”指针或一个“头部”副本,并设置头部或尾部或某物到最近的newnode值。然后,您可以设置tail->next = newnode; tail = newnode;这将不断扩展您的列表,而不是每次覆盖相同的head-> next。