c - 我不明白deleteall(key)函数中这条语句 "cur = prev->next;"的逻辑

标签 c linked-list singly-linked-list

该程序创建一个在开头插入的链表,并具有一个 deleteall(key) 函数,该函数将删除具有该键值的所有节点

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

struct node{

    int data;
    struct node* next; //creation a linked list with insertion at beginning
};

struct node* head = NULL;
int totaldeleted = 0;


void create(n) {

    int i;
    struct node *newnode, *temp;
    newnode = (struct node*)malloc(sizeof(struct node));
    printf("Enter the data: ");
    scanf("%d", &newnode -> data);
    newnode -> next = NULL;

    if(head==NULL){
        head=newnode;    
    }

    temp = head;
    for(i=2; i<=n; i++){
        int data;
        newnode = (struct node*)malloc(sizeof(struct node));
        printf("Enter the data: ");
        scanf("%d", &data);

        newnode -> data = data;
        newnode -> next = NULL;

        newnode -> next = head;
        head = newnode;
    }
}

void display(){

    struct node* temp;
    printf("\nThe Linked list is: ");
    temp = head;

    while(temp!= NULL){
        printf("%d", temp -> data);
        temp = temp -> next;
    }

}

int deleteall(key){ 

    struct node *prev, *cur;
    if(head == NULL){
        prev = NULL;
        cur = NULL;
        printf("\nList is empty!");
    }

    while(head != NULL && head->data == key){
        prev = head;
        head = head -> next;
        free(prev);
        totaldeleted++;   

    }
    prev = NULL;
    cur = head;

    while(cur != NULL){

        if(cur->data == key && prev != NULL){
               prev -> next = cur->next;
               free(cur);
               cur = prev->next; // I cannot understand this logic.
               totaldeleted++;
        }
        else {

         prev = cur;
        cur = cur -> next;

        }
    }
    return totaldeleted;
}

int main(){
    int n, key;

    printf("Enter the number of nodes: ");
    scanf("%d", &n);

    create(n);
    display();
    printf("\nEnter the key: ");
    scanf("%d", &key);
    totaldeleted = deleteall(key); 
    printf("Total deleted: %d", totaldeleted);
    display();

    printf("\n");

}

最佳答案

就在该行之前,cur 指向已删除节点 - 该节点现已释放,因此 cur 指针的值不确定。我们希望将 cur 指向已删除节点后面的节点。如果它没有被删除,我们可以从cur->next获取它。但是,cur->next 无效。我们可以在 free...

之前使用一个临时变量来存储 cur->next 的值

但是,在free之前有这样一行:

prev -> next = cur->next;

即现在我们需要的值已经分配到了 prev->next 中,因此我们不需要临时变量,但可以从 prev->next 中获取它。

关于c - 我不明白deleteall(key)函数中这条语句 "cur = prev->next;"的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579890/

相关文章:

python - 对 python -c 打印命令感到困惑 "\xef\xbe\xad\xde"这是什么意思?

c 中带有 select 的并发服务器 TCP

c - 在 linux 中修改目标文件函数 xref 的优雅方式

data-structures - 高效实现不可变(双重)链表

c++ - C++ 标准库或其他广泛使用的库中的单链表?

c - 未找到架构 x86_64 的 Eclipse C 构建错误符号

c - 链表实现内存分配

c - 使用递归删除链表中所有出现的数字

c - 如何仅使用两个指针来反转单向链表?

c - 为什么我的程序突然终止?