I have some problem about add and delete node in linked list without malloc. I delete node then add node again and print list but nothing happen. T try to check add_node function and it work normally but I can not check with del_node. Here is my code:
#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);
}
}
Thanks all.
CodePudding user response:
regarding your delete function: this code line doesnt do what i think you want it to do:
temp = temp->next;
youre trying to change local variable which is lost anyway when youre out of the function scope
try this fix: after you initialized temp add this line
node *prev = temp
in youre while loop the first line should be:
prev = temp;
and then outside the loop instead:
temp = temp->next;
put this line:
prev->next = temp->next;