gpt4 book ai didi

c - 用于创建链表的数组

转载 作者:行者123 更新时间:2023-11-30 17:15:48 26 4
gpt4 key购买 nike

typedef struct num{
int num;
int pre;
struct num* next;
}Num;

Num list[10]=
{{3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0}
};

#include <stdio.h>

int main(){

int cnt;
Num *ptr = NULL;

Num tempTwo;
for (cnt = 0; cnt < 10; cnt++) {
tempTwo = list[cnt];
ptr->next = &tempTwo; //Error
ptr = ptr->next;
}

for (cnt = 0; cnt<10; cnt++) {
printf("num: %d, pre: %d\n",ptr->num,ptr->pre);
ptr = ptr->next;
}
}

我想使用指针 ptr 创建带有数组“list”的链表。

Error: Bad access

我该如何解决这个问题?

最佳答案

这应该可以解决问题

#include <stdio.h>

typedef struct num{
int num;
int pre;
struct num* next;
}Num;

Num list[10]= {
{3,4},{2,1},{6,5},{7,2},{4,3},{3,9},{5,6},{1,3},{8,4},{10,0}
};

int main(){

int cnt;
Num *head, *ptr;

list[9].next = NULL; // marks the end of the list
for (cnt=8; cnt>=0; cnt--)
list[cnt].next = &list[cnt+1]; // point to next list item
head = &list[0]; // point to first list item

// test
ptr = head;
while (ptr) {
printf ("%d %d\n", ptr->num, ptr->pre);
ptr = ptr->next;
}
return 0;
}

程序输出:

3 4
2 1
6 5
7 2
4 3
3 9
5 6
1 3
8 4
10 0

关于c - 用于创建链表的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com