在C seg故障错误中附加链表

时间:2015-06-01 02:01:12

标签: c struct linked-list append

我在链接列表的末尾添加整数时遇到了一些麻烦。我是C的新手,我的部分程序正常工作(推送功能)。我想返回一个指向struct节点的指针,我不太确定我的append函数出错了。

〜感谢。

 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;
     }

1 个答案:

答案 0 :(得分:2)

我认为缺少的是函数的递归部分需要设置current-&gt; next。这样就可以将每个节点的下一个指针设置为它到达列表末尾的指针,当它被设置为新的malloced节点时。

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;
       }
}