数组列表到C中的链表节点
我想知道O1时代的链表是否可行,并找到了上面的链接。我不懂java,但确实懂点C++,而不是C++。有人能解释一下这个概念的方法吗?如何对数组进行编码以指向链接列表?根据我的知识,我认为我了解如何将节点存储在**数组中,但不确定如何将其连接到同样具有这些节点的*列表。这里是一个简单的示例数组列表到C中的链表节点,c,arrays,pointers,linked-list,C,Arrays,Pointers,Linked List,我想知道O1时代的链表是否可行,并找到了上面的链接。我不懂java,但确实懂点C++,而不是C++。有人能解释一下这个概念的方法吗?如何对数组进行编码以指向链接列表?根据我的知识,我认为我了解如何将节点存储在**数组中,但不确定如何将其连接到同样具有这些节点的*列表。这里是一个简单的示例 #include<stdio.h> #include<stdlib.h> struct node { int id; struct node *next
#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;
}
TBH,我不明白这种结构的意义。在什么情况下,它比简单的按节点值排序的节点指针列表/数组更有利?这种数据结构似乎没有任何优势。如果要维护数组,则可以通过索引直接查找,但不能有效地删除项。同时维护一个数组和一个双链表似乎并没有比只维护一个数组有任何优势。我很好奇O1中的链表在C中是否可行,但我想它不是。。。如果我想移动周围的值,它不会是O1 for array方法,因为我必须遍历它。在链表中找到我想要移位的值也不是O1,因为我也必须遍历它。O1中的链表是什么?如果没有实际操作,谈论复杂性是没有意义的。