我在将整数添加到链表的末尾时遇到了一些麻烦。我是非常新的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;
}
我认为缺少的是函数的递归部分需要设置current->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;
}
}