单链表删除不了元素是为什么

单链表实现不了删除,前面的代码是书上的跟着敲的,我觉得可能是主函数里面错了,但是不知道怎么搞

img

img

99和100行交换啊,先输入j再删除啊

以下内容部分参考ChatGPT模型:


首先,需要看一下实现删除的代码,可能存在错误。以下是单链表删除元素的示例代码:

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

struct node {
    int data;
    struct node *next;
};

struct node* create_list(int n);
void display_list(struct node *head);
struct node* delete_node(struct node *head, int key);

int main()
{
    int n, key;
    struct node *head = NULL;

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

    head = create_list(n);

    printf("\nData in the list \n");
    display_list(head);

    printf("\nEnter the element to delete: ");
    scanf("%d", &key);

    head = delete_node(head, key);

    printf("\nData in the list after deletion \n");
    display_list(head);

    return 0;
}

struct node* create_list(int n)
{
    int i;
    struct node *head = NULL;
    struct node *temp = NULL;
    struct node *p = NULL;

    for(i=0; i<n; i++)
    {
        temp = (struct node*)malloc(sizeof(struct node));
        printf("Enter the data for node %d: ", i+1);
        scanf("%d", &temp->data);
        temp->next = NULL;

        if(head == NULL)
        {
            head = temp;
        }
        else
        {
            p = head;
            while(p->next != NULL)
            {
                p = p->next;
            }
            p->next = temp;
        }
    }

    return head;
}

void display_list(struct node *head)
{
    struct node *p = head;

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

struct node* delete_node(struct node *head, int key)
{
    struct node *p = head;
    struct node *temp = NULL;

    if(head == NULL)
    {
        printf("List is empty");
        return NULL;
    }

    if(head->data == key)
    {
        temp = head;
        head = head->next;
        free(temp);
        return head;
    }

    while(p->next != NULL)
    {
        if(p->next->data == key)
        {
            temp = p->next;
            p->next = temp->next;
            free(temp);
            return head;
        }
        p = p->next;
    }

    printf("Element %d not found\n", key);
    return head;
}

在这个示例代码中,首先创建一个单链表,然后打印出链表中的元素。然后从用户输入中读取要删除的元素,然后删除链表中的元素并打印出删除后的链表。

在删除元素的函数中,首先检查链表是否为空。如果是,则打印消息并返回NULL,否则继续查找要删除的元素。如果要删除的元素是第一个元素,则将头指针指向下一个元素。否则,遍历链表并查找要删除的元素。如果找到了要删除的元素,则将前一个元素的指针指向下一个元素,并释放该元素的内存。

如果没有找到要删除的元素,则打印消息并返回头指针。


如果我的建议对您有帮助、请点击采纳、祝您生活愉快