【问题标题】:array to create a linked-list数组来创建一个链表
【发布时间】:2015-04-25 17:10:49
【问题描述】:
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

我能做些什么来解决这个问题?

【问题讨论】:

  • ptr-&gt;next = &amp;tempTwo; 产生错误,因为您在第一次循环迭代之前设置了Num *ptr = NULL;
  • 但是 Xcode 会进行初始化,如果我不这样做,num 只是 10,pre 总是 0。
  • 你不能用NULL指针指向任何东西:它没有目标。
  • 你熟悉malloc吗?
  • 是的。删除 NULL 然后 Xcode 打印结果。但 num 始终为 10,pre 始终为 0。

标签: c arrays linked-list


【解决方案1】:

这应该可以解决问题

#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

【讨论】:

  • 我不必那样做,因为数组已经存在。但是通常将一个项目添加到简单链表最简单的方法是将它添加到前面,然后在打印列表时它会以相反的顺序出现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 2012-11-30
  • 2018-10-16
  • 2020-04-22
  • 1970-01-01
相关资源
最近更新 更多