2014-02-14 120 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

謝謝布魯塞爾 –