请看代码加注释的部分,为什么按照它不能完成遍历,得改成next?逻辑出现错误了吗?

#include
#include
#include
typedef struct Node {
int data;
struct Node * next;
}Node;
typedef struct List {
Node * head, *tail;
}List;
void listInsert(List *l, int a) {
if (!l) {
return;
}
else if (!l->head) {
l->head = (Node *)malloc(sizeof(Node));
l->head->data = a;
l->head->next = nullptr;
l->tail = l->head;
}
else {
Node * p = (Node *)malloc(sizeof(Node));
p->data = a;
p->next = nullptr;
l->tail = p;
Node * temp = l->head;

    //为什么这种循环方式就只能遍历一个结点,有什么逻辑错误吗?
    /*while (temp) {
        temp = temp->next;
    }
    temp=p*/

    while (temp->next) {
        temp = temp->next;
    }
    temp->next= p;
}

}
void listTravel(List * l) {
if (!l) {
return;
}
else if (!l->head) {
return;
}
else {
while (l->head) {
printf("%d", l->head->data);
l->head = l->head->next;
}
}
}
int main() {
List l;
l.head = l.tail = nullptr;
listInsert(&l, 1);
listInsert(&l, 2);
listInsert(&l, 3);
listInsert(&l, 4);
listInsert(&l, 5);
listTravel(&l);
return 0;
}


while (temp)
相当于while (temp == NULL) 函数当然不执行
->
while (!temp)

不好意思,看错了。你那么写应该没问题,但是插入链表也许有问题。

else {
Node * p = (Node )malloc(sizeof(Node));
p->data = a;
p->next = nullptr;
l->tail->next = p; //这里给下一节点地址
l->tail=p;
Node * temp = l->head;
//为什么这种循环方式就只能遍历一个结点,有什么逻辑错误吗?
/*while (temp) {
temp = temp->next;
}
temp=p
/

while (temp->next) {
    temp = temp->next;
}
temp->next= p;

}
}

①istInsert(&l, 1); 执行时,按照下面的代码 处理逻辑, l->head->next = nullptr; 同时对应l->head 也不是nullptr了
/**************************************/
if (!l->head) {
l->head = (Node *)malloc(sizeof(Node));
l->head->data = a;
l->head->next = nullptr; // 设定陈过了NULLptr
l->tail = l->head;
}
listInsert(&l, 1);

②再执行listInsert(&l, 2);
listInsert(&l, 3);
listInsert(&l, 4);
listInsert(&l, 5); 时, 从来就没有修正过 l->head->next 对应的指向内容, 还是保留步骤②的结果l->head->next =nullptr。同时下面 判断的
temp = l->head;所以导致了*while (temp) {
temp = temp->next;
}只能执行一次了 。
/**************************************/
Node * p = (Node *)malloc(sizeof(Node));
p->data = a;
p->next = nullptr;
l->tail = p;
Node * temp = l->head;

//为什么这种循环方式就只能遍历一个结点,有什么逻辑错误吗?
/*while (temp) {
    temp = temp->next;
}
temp=p*/

while (temp->next) {
    temp = temp->next;
}
temp->next= p;

}
/***************************************/

订正:
错误:
还是保留步骤②的结果l->head->next =nullptr。
正确:
还是保留步骤①的结果l->head->next =nullptr。