2014-02-14 37 views
1

嗨我希望实现一个简单的链表和所有的值到列表的末尾。虽然这么简单,但我无法做到这一点。你能告诉我我在哪里做错了吗?最初我正在声明一个指针并为其分配NULL值。后来在每次迭代中,我都将内存分配给最初为NULL的指针。实现简单的链接列表

#include <stdio.h> 
#include <malloc.h> 

struct node{ 
    int a; 
    struct node* next; 
}; 
struct node* insert(struct node* start,int value); 
void print(struct node* head); 
int main() 
{ 
    int a; 
    struct node* head = NULL; 
    while(scanf("%d",&a) != EOF)//taking input 
    { 
     head = insert(head,a); 
     print(head); 
    } 
    return 0; 
} 

struct node* insert(struct node* start,int value) 
{ 
    struct node* head = start; 
    while(start != NULL) 
    { 
     start = start->next;//getting upto the end of the linked list 
    } 
    start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end 
    start->a = value; 
    start->next = NULL; 
    if(head == NULL) 
    { 
     return start;//for the base case when list is initally empty 
    } 
    return head; 
} 

void print(struct node* head) 
{ 
    while(head != NULL) 
    { 
     printf("%d\n",head->a); 
     head = head->next; 
    } 
    return; 
} 
+0

[似曾相识](http://stackoverflow.com/q/21762488/369450) – cpburnz

+1

请注意'malloc.h'不达标。你应该使用'stdlib.h' – ajay

+0

好的,我会在之后记住这一点。谢谢 –

回答

1

你失去你的尾巴和你的新节点之间的联动,试试这个,而不是

struct node* insert(struct node* head,int value) 
{ 
struct node* tail = head; 
while(tail != NULL && tail->next != NULL) 
{ 
    tail= tail->next;//getting upto the end of the linked list 
} 

struct node* start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end 
start->a = value; 
start->next = NULL; 
if(head == NULL) 
{ 
    return start;//for the base case when list is initally empty 
} 
else 
{ 
    tail->next = start; 
} 
return head; 
} 
+0

谢谢,但我现在仍然能够找出我的错误。请帮帮我。 –

+0

你的意思是说“start =(struct node *)malloc(sizeof(struct node));”导致链接丢失,但是在“start-> next =(struct node *)malloc(sizeof(struct node))”完成时会保留链接吗? –

+0

是的。你可以最初处理你想要的变量,但在某些时候你必须分配start-> next,这是你在代码中没有做的。我简单地重新定义了它,并更改了变量名,以便稍微简单一些。 – jakebower

0
struct node* insert(struct node* start,int value){ 
    struct node* head = start; 
    struct node* np = (struct node*)malloc(sizeof(struct node)); 
    np->a = value; 
    np->next = NULL; 

    if(head == NULL) 
     return np; 

    while(start->next != NULL){ 
     start = start->next; 
    } 
    start->next = np; 
    return head; 
} 

是什么让我使用越野车的办法?

nodeX 
| 
+a 
| 
+next(address to OtherX) 

nodeX.next = new_node;//update link(case of OK) 

tempPointer = nodeX.next;//address to OtherX set to tempPointer 
tempPointer = new_node;//contents of tempPointer changed, but orignal (nodeX.next not change) 
+0

谢谢,但为什么开始 - >下一步,但不能以这样的方式开始指向NULL,然后改变它的方式,我正在做的方式的代码。是什么让我使用越野车的方法? –

+1

@ user1244590如果将地址设置为局部变量,则会将其丢弃。必须把正确的链接。 – BLUEPIXY

+0

谢谢布鲁塞尔 –