2015-06-01 39 views
0

我在將整數添加到鏈接列表的末尾時遇到了一些麻煩。我對C非常陌生,並且我的程序的一部分工作正常(push功能)。我想返回一個指向結構節點的指針,我不太清楚我的追加函數中出錯的位置。在C seg錯誤中添加鏈接列表

〜謝謝。

enter code here 


//node.h 

#ifndef NODE_H 
#define NODE_H 

struct node{ 
    int val; 
    struct node *next; 
}; 

int length(struct node *); 
struct node* push(struct node *, int);  //adds integer to front of list. 
struct node* append(struct node *, int); //adds integer to back of list. 
void print(struct node *, int); 

#endif 


//node.c 

#include "./node.h" 
#include<stdlib.h> 
#include<stdio.h> 

int length(struct node *current){ 
    if(current->next != NULL) 
    return 1 + length(current->next); 
else 
    return 1; 
} 

struct node* push(struct node *head, int num){ 

    struct node *temp = malloc(sizeof(struct node)); 
    temp->val = num; 
    temp->next = head; 
    head = temp; 
    temp = NULL; 
    return head; 
    } 

    struct node* append(struct node *current, int num){ 

     if(current != NULL){ 
     append(current->next, num); 
     } 

     else{ 
     struct node* temp = malloc(sizeof(struct node)); 
     temp->val = num; 
     temp->next = NULL; 
     current = temp; 
     return current; 

     } 
     } 



void print(struct node* head, int size){ 

    printf("The list is %i", size); 
    printf(" long \n"); 
    struct node* temp; 
    temp = head; 
    while(temp != NULL){ 
    printf("%d", temp->val); 
    printf(" "); 
    temp = temp->next; 
    } 
    printf(" \n"); 
    } 


    //Main 

    #include "./node.h" 
    #include<stdlib.h> 
    #include<stdio.h> 

    int main(){ 

    char ans[2]; 
    int num; 
    struct node* head = NULL; 

    do{ 
    printf("Enter a integer for linked list: "); 
    scanf("%d", &num); 

    head = append(head, num); 
    printf("Add another integer to linked list? (y or n) "); 
    scanf("%1s", ans); 
    }while(*ans == 'y'); 

    print(head, length(head)); 

    return 0; 
    } 

回答

2

我覺得現在缺少的是該函數的遞歸部分需要設置下一個電流 - >。這有一個效果,即將每個節點的下一個指針設置爲它所處的位置,直到到達列表的末尾,並將其設置爲新配置的節點。

struct node* append(struct node *current, int num){ 

     if(current != NULL){ 
     current->next = append(current->next, num); 
     return current; 
     } 
     else { 
     struct node* temp = malloc(sizeof(struct node)); 
     if (temp == NULL) abort(); 
     temp->val = num; 
     temp->next = NULL; 
     return temp; 
     } 
} 
+1

或者,跳過遞歸併使用[迭代循環](http://pastebin.com/8Y3byztd)。 – WhozCraig