不知道为什么网站删了我的提问,再来一次:请看代码加注释的部分,为什么按照它不能完成遍历,得改成next?逻辑出现错误了吗?

rkakar 2016-10-24 06:56:18
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
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;
}
...全文
225 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
rkakar 2016-10-24
  • 打赏
  • 举报
回复
谢谢,搞明白了
youyu157 2016-10-24
  • 打赏
  • 举报
回复
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->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; } }

3,424

社区成员

发帖
与我相关
我的任务
社区描述
其他开发语言 其他开发语言
社区管理员
  • 其他开发语言社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧