【发布时间】:2021-12-27 05:20:46
【问题描述】:
我有一些关于在没有 malloc 的链表中添加和删除节点的问题。我删除节点然后再次添加节点并打印列表但没有任何反应。 T 尝试检查 add_node 函数,它工作正常,但我无法检查 del_node。这是我的代码:
#include <stdio.h>
#include <stdint.h>
#define MAX_NODES 20
typedef struct node
{
uint8_t value;
struct node *next;
}
node;
static node node_arr[MAX_NODES] = {[0 ... 19] = 0};
static uint8_t next_node = 0;
void Add_Node(node **head, uint8_t val, uint8_t index)
{
node *new_node = &(node_arr[index]);
next_node++;
new_node->value = val;
new_node->next = *head; /* New node will point the current head*/
*head = new_node; /* Make new node become head of the list */
}
void Del_Node(node **head, uint8_t index)
{
uint8_t run = 0; /* Use run for reaching position */
node *temp = *head;
while((temp->next!= NULL) && (run != index)){
temp = temp->next;
run++;
}
temp = temp->next; /* Let current node become next node */
next_node --;
}
int main(){
node *head = NULL;
Add_Node(&head, 2, 1);
Add_Node(&head, 3, 2);
Add_Node(&head, 4, 3);
Add_Node(&head, 5, 4);
Del_Node(&head, 3); // position 3 mean value 3 of list
for (node *temp = head; temp != NULL; temp = temp->next)
{
printf(" %d ", temp->value);
}
}
谢谢大家。
【问题讨论】:
-
temp = temp->next; /* Let current node become next node */。这并没有做任何事情,因为它只是设置了一个局部变量。需要将前一个节点的next指针改为指向temp->next。 -
next_node没有用于任何用途。它只是增加和减少。要正确使用数组,您需要保留一个空闲列表。最初,空闲列表包含node_arr的所有节点。Add_Node函数应该从空闲列表中删除第一个节点,并将其添加到工作列表中。Del_Node函数应该从工作列表中删除节点,并将其添加到空闲列表中。 -
@user3386109 next_node 这里我用于其他目的。感谢您的帮助
-
@kaylum 我确定我错了(我的程序),但我想知道我使用了双指针(通过引用传递)并且它不起作用
标签: arrays c function linked-list static