为什么会出现写入访问权限冲突。 tail 是 nullptr?

Re:从零开始的代码生活
全栈领域新星创作者
2021-02-09 04:21:39
题目要求将链表逆置,输入-1结束。

代码:
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
int data;
struct ListNode* next;
};

struct ListNode* createlist();
struct ListNode* reverse(struct ListNode* head);
void printlist(struct ListNode* head)
{
struct ListNode* p = head;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}

int main()
{
struct ListNode* head;

head = createlist();
head = reverse(head);
printlist(head);

return 0;
}
struct ListNode* createlist()
{
struct ListNode* head = NULL, * tail = NULL, * p = NULL;
int data;
scanf("%d", &data);
while (data != -1)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->data = data;
p->next = NULL;
if (head == NULL)
head = p;
else
tail->next = p;
tail = p;
scanf("%d", &data);
}
return head;
}
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* ptr1, * ptr2, * heado = NULL, * tail = NULL;
int a[100], index = 0;
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
a[index++] = ptr1->data;
for (int i = index - 1; i >= 0; i--)
{
ptr2 = (struct ListNode*)malloc(sizeof(struct ListNode));
ptr2->data = a[i];
ptr2->next = NULL;
if (heado = NULL)
heado = ptr2;
else
tail->next = ptr2;
tail = ptr2;
}
return heado;
}

...全文
896 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 1 楼 Simple-Soft的回复:
if (heado = NULL)
heado = ptr2;
else
tail->next = ptr2;
这里错了,应该为if (heado == NULL)
自己看了半个小时没看出来竟然犯了这么低级的错误,谢谢哈
自信男孩 2021-02-09
  • 打赏
  • 举报
回复
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* ptr1, * ptr2, * heado = NULL, * tail = NULL;
int a[100], index = 0;
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next)
a[index++] = ptr1->data;
for (int i = index - 1; i >= 0; i--)
{
ptr2 = (struct ListNode*)malloc(sizeof(struct ListNode));
ptr2->data = a[i];
ptr2->next = NULL;
//if (heado = NULL)
if (heado == NULL)
heado = ptr2;
else
tail->next = ptr2;
tail = ptr2;
}
return heado;
}

供参考~

=不是比较==是比较
Simple-Soft 2021-02-09
  • 打赏
  • 举报
回复
if (heado = NULL)
heado = ptr2;
else
tail->next = ptr2;
这里错了,应该为if (heado == NULL)

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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