我不明白“ cur = prev-> next;”这句话的逻辑。在deleteall(key)函数中

时间:2018-07-29 11:31:31

标签: 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");

}

1 个答案:

答案 0 :(得分:0)

就在该行之前,cur指向 deleted 节点-该节点现在已释放,因此cur指针的值不确定。我们想将cur指向跟随已删除节点的节点。如果未删除,我们可以从cur->next获取。但是,cur->next无效。我们可以使用一个临时变量在cur->next ...

之前存储free的值。

但是,在free之前有以下一行:

prev -> next = cur->next;

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