用于创建链表的数组

时间:2015-04-25 17:10:50

标签: c arrays linked-list

Uri.parse("android.resource://" + getPackageName() + "/raw/file_name");

我想用数组' list'制作链表。使用指针ptr。

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;
    }
}

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题

#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