#include<stdio.h>
#include<stdlib.h>

typedef struct list {
    int data;
    struct list *next;
} node;

void add(node **head, node **tail, int data) {
    node *temp1, *temp2;
    temp1 = (node*) malloc(sizeof(struct list));
    temp1->data = data;
    temp1->next = NULL;

    if (*head == NULL) {
        *head = temp1;
        *tail = temp1;
    } else {
        for (temp2 = *head; temp2->next != NULL; temp2 = temp2->next)
            temp2->next = temp1;
        *tail = temp1;
    }
}

int main() {
    node *temp, *head, *tail;
    head = NULL;
    add(&head, &tail, 1);
    add(&head, &tail, 2);
    add(&head, &tail, 3);
    add(&head, &tail, 4);

    for (temp = head; temp != (node *) 0; temp = temp->next) {
        printf("[%d]->", (temp->next));
    }
    printf("[NULL]\n\n");
}

错误是什么?为什么不打印?
错误是什么?为什么只打印[0]>NULL?我试过各种形式,但我做不到。怎么了?
指针有问题吗?或者没有分配足够的内存?

最佳答案

您在for循环中缺少一个语句:

for(temp2=*head; temp2->next!=NULL; temp2=temp2->next)
temp2->next=temp1;
*tail=temp1;

这将作为
for(temp2=*head; temp2->next!=NULL; temp2=temp2->next) {
    temp2->next=temp1;
}
*tail=temp1;

你只需为({})或;添加一个空块就可以修复它
for(temp2=*head; temp2->next!=NULL; temp2=temp2->next) {}
temp2->next=temp1;
*tail=temp1;

另外,您在printf语句中想要的可能是
printf("[%d]->",(temp->data));

10-08 08:23
查看更多