修改如下:
#include <stdio.h>
#include <stdlib.h>
struct cell
{
int x;
struct cell* next;
};
struct cell* build(void)
{
struct cell* head, * p, * tmp;
int n;
head = tmp = p = NULL;
scanf("%d", &n);
while (n != 0)
{
p = (struct cell*)malloc(sizeof(struct cell));
p->next = NULL;
p->x = n;
if (head == NULL)
{
head = p;
tmp = p;
}
else
{
tmp->next = p;
tmp = p;
}
scanf("%d", &n);
}
return head;
}
void print(struct cell* head)
{
if (head != NULL)
{
printf("%d", head->x);
print(head->next);
}
}
void release(struct cell* head)
{
struct cell* t;
if (head != NULL)
{
t = head->next;
free(head);
release(t);
}
}
int main(void)
{
struct cell* head;
head = build();
if (head != NULL)
print(head);
else
printf("NULL");
release(head);
return 0;
}
复制的代码中带入了格式,把红线部分删掉,手动输入。
head是头节点,是绝对不要改的,你没事老改head,这链表不被你改的乱七八糟了吗,那head还指向头吗
两个节点,一个head一个p,head指向头,p指向尾,你要不断的new p,移动p,而不是移动head
你还是找个典型的建立链表的代码好好看看
如果只看代码想不明白,那找张纸画一画,琢磨一下每一步指针到底应该怎么变
不要什么都凭直觉
-=-=-=
你现在这个代码是先建立了个尾节点,然后每次new一个p就让p指向这个尾,这样建立出来的表整个是逆序的
修改如下,供参考:
#include <stdio.h>
#include <malloc.h>
struct cell {
int x;
struct cell* next;
};
struct cell* build(void)//新建单链表并将建好的单链表首结点地址返回
{
struct cell* head, * tmp, * p;
head = tmp = p = NULL;
int n;
/*请在以下位置补充完整,实现函数build的功能*/
while (1)
{
scanf("%d", &n);
if (n == 0) break;
p = (struct cell*)malloc(sizeof(struct cell));
p->next = NULL;
p->x = n;
if (!head)
head = p;
else
tmp->next = p;
tmp = p;
}
return head;
}
void print(struct cell* head)//打印整个单链表
{
/*请在以下位置补充完整,实现函数print的功能*/
struct cell* p = head;
if (!p)
printf("NULL");
else {
while (p) {
printf(p == head ? "%d" : " %d", p->x);
p = p->next;
}
}
}
void release(struct cell* head)//释放单链表空间
{
/*请在以下位置补充完整,实现函数release的功能*/
if (!head)
return;
release(head->next);
free(head);
}
int main()
{
struct cell* head;
head = build();
print(head);
release(head);
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!