数组列表到C中的链表节点

时间:2017-10-05 04:45:07

标签: c arrays pointers linked-list

Arraylist mapping to linkedlist nodes

我想知道O(1)时间内的链表是否可行并找到上面的链接。我不知道java,但知道一点C,而不是C ++。有人可以解释这个概念的方法吗?你如何编码数组指向链表?根据我的知识,我想我理解如何将节点存储在**数组中但不知道它如何连接到也具有相同节点的*列表。

1 个答案:

答案 0 :(得分:1)

这是一个简单的例子。

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

struct node {
        int id;
        struct node *next;
        struct node *prev;
};
struct node *nodearray[100];
static struct node *head = NULL, *tail = NULL;

void insert_node (struct node **node,int id) {
        struct node *new = NULL;
        new = malloc(sizeof(*new));
        new->id = id;
        if (head == NULL) {
                head = new;
                new->prev = NULL;
        } else {
                tail->next = new;
                new->prev = tail;
        }
        tail = new;
        printf("Added [%d] at %p\n", id, new);
        new->next = NULL;
        *node = new;
}
void delete_node (int id) {
        struct node *node_to_del , *prev, *next;
        node_to_del = nodearray[id];
        if(!node_to_del)
            return;
        printf("Del %p\n", node_to_del);
        if (node_to_del == head) {
            head = node_to_del->next;
            node_to_del->next->prev = NULL;
        } else if (node_to_del == tail) {
            tail = node_to_del->prev;
            node_to_del->prev->next = NULL;
        } else {
        prev = node_to_del->prev;
        next = node_to_del->next;
        prev->next = next;
        next->prev = prev;
        }
        free(node_to_del);
       node_to_del = NULL;
        nodearray[id] = NULL;

}
struct node* find_node (int id) {
    return nodearray[id];
}

void list_node(void) {
        struct node *ptr = head;
        while(ptr) {
                printf("ptr[%d]  %p\n", ptr->id, ptr);
                ptr = ptr->next;
        }
}

int main () {

        insert_node(&nodearray[1] ,1);
        insert_node(&nodearray[2] ,2);
        insert_node(&nodearray[3] ,3);
        insert_node(&nodearray[4] ,4);
        insert_node(&nodearray[5] ,5);

        printf("1 at %p \n", nodearray[1]);
        printf("2 at %p \n", nodearray[2]);
        printf("3 at %p \n", nodearray[3]);
        printf("4 at %p \n", nodearray[4]);
        printf("5 at %p \n", nodearray[5]);

        delete_node(1);
        delete_node(2);
        delete_node(4);

        list_node();

        printf("1 at %p \n", nodearray[1]);
        printf("2 at %p \n", nodearray[2]);
        printf("3 at %p \n", nodearray[3]);
        printf("4 at %p \n", nodearray[4]);
        printf("5 at %p \n", nodearray[5]);

        printf("node at 5 = %p\n", nodearray[5]);

        return;
}