关于单链串删除字所有字符等于a的问题

img

img

img

img

img


为什么最后不能运行遍历的结果,只能完成删除字符的那个算法,后面遍历的算法没有完成

删除函数修改如下,供参考:

bool Delete_L(SLinkString &S, char ch)
{
    SLinkString p = S->next, q = S, m = NULL;
    while (p){
        if (p->str == ch){
            m = p;
            p = p->next;
            q->next = p;
            free(m);
        }
        else{
            q = p;
            p = p->next;
        }
    }
    return true;
}

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

struct SLinkString {
    char str;
    SLinkString *next;
};

bool Delete_L(SLinkString &S) {
    SLinkString *prev = NULL;
    SLinkString *curr = &S;

    while (curr != NULL) {
        if (curr->str == 'a') {
            if (prev == NULL) {
                // Removing the first node
                S = *(S.next);
                free(curr);
                curr = &S;
            } else {
                // Removing a non-first node
                prev->next = curr->next;
                free(curr);
                curr = prev->next;
            }
        } else {
            prev = curr;
            curr = curr->next;
        }
    }

    return true;
}

int main() {
    // Create a sample list
    SLinkString *head = (SLinkString *)malloc(sizeof(SLinkString));
    head->str = 'b';

    SLinkString *second = (SLinkString *)malloc(sizeof(SLinkString));
    second->str = 'a';
    head->next = second;

    SLinkString *third = (SLinkString *)malloc(sizeof(SLinkString));
    third->str = 'c';
    second->next = third;

    SLinkString *fourth = (SLinkString *)malloc(sizeof(SLinkString));
    fourth->str = 'a';
    third->next = fourth;

    fourth->next = NULL;

    // Print the original list
    printf("Original List: ");
    SLinkString *curr = head;
    while (curr != NULL) {
        printf("%c ", curr->str);
        curr = curr->next;
    }
    printf("\n");

    // Delete all 'a' nodes
    Delete_L(*head);

    // Print the modified list
    printf("Modified List: ");
    curr = head;
    while (curr != NULL) {
        printf("%c ", curr->str);
        curr = curr->next;
    }
    printf("\n");

    return 0;
}