我有一些關于在沒有 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);
}
}
謝謝大家。
uj5u.com熱心網友回復:
關于您的洗掉功能:此代碼行沒有執行我認為您希望它執行的操作:
temp = temp->next;
你試圖改變區域變數,當你離開函式作用域時,它無論如何都會丟失
試試這個修復:在你初始化 temp 后添加這一行
node *prev = temp
在你的 while 回圈中,第一行應該是:
prev = temp;
然后在回圈之外:
temp = temp->next;
把這一行:
prev->next = temp->next;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/357602.html
