2020-05-29 17:13

# 大佬能帮下忙吗？ 单链表出现的读取访问权限冲突

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

typedef struct LNode {
int elem;
struct LNode* next;
}Node, * List;

List init() {
List list = (List)malloc(sizeof(Node));
list->elem = 0;   list->next = NULL;
return list;
}

int length(List list) {
return list->elem;
}

bool isEmpty(List list) {
return list->next == NULL;
}

void add(List list, int elem) {
Node node = { elem,NULL };
node.next = list->next;
list->next = &node;
list->elem++;
}

void append(List list, int elem) {
Node node = { elem,NULL };
List cur = (List)malloc(sizeof(Node));
cur = list->next;
while (cur != NULL) {
cur = cur->next;
}//结束while语句后，cur是一个nullptr
cur = &node;
list->elem++;
}

int* travel(List list) {
int* num = (int*)malloc(sizeof(int) * length(list));//初始化num数组
int i = 1;
if (isEmpty(list)) {
printf("链表为空！");
num = NULL;
}
else {
List cur = (List)malloc(sizeof(Node));
if (!cur) {
printf("申请内存失败！");
exit(0);
}
cur = list->next;
while (cur != NULL) {
printf("链表第%d个节点为：%d\n", i, cur->elem);
num[i - 1] = cur->elem;
i++;
cur = cur->next;
}
}
return num;
}

int main() {
List list = init();
append(list, 4);
printf("链表是否为空：%d\n", isEmpty(list));
printf("链表长度为:%d\n", length(list));
travel(list);
return 0;
}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 1条回答

• bobhuang 10月前