浙大版《C语言程序设计(第3版)》题目集 习题11-8 单链表结点删除 (20分)

在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
    int data;
    struct ListNode *next;
};
struct ListNode *readlist();
struct ListNode *deletem(struct ListNode *L, int m);
void printlist(struct ListNode *L)
{
    struct ListNode *p = L;
    while (p)
    {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}
int main()
{
    int m;
    struct ListNode *L = readlist();
    scanf("%d", &m);
    L = deletem(L, m);
    printlist(L);
    return 0;
}
struct ListNode *readlist()
{
    struct ListNode *head, *tail, *p;
    head = tail = NULL;
    while (1)
    {
        p = (struct ListNode *)malloc(sizeof(struct ListNode));
        scanf("%d", &(p->data));

        if (p->data < 0)
            break;
        p->next = NULL;
        if (head == NULL)
            head = p;
        else
            tail->next = p;
        tail = p;
    }
    return head;
}
struct ListNode *deletem(struct ListNode *L, int m)
{
    struct ListNode *p, *head;
    while (1)
    {
        if (L == NULL || L->data != m)
        {
            head = L;
            break;
        }
        else if (L->data == m) //此处的if else同样是为了防止L是空集
            L = L->next;
    }
    if (head == NULL || head->next == NULL) //借助||的左结合性先判断head是否是空集防止出现head是空地址却head-》next
        return head;
    while (1)
    {
        if (L == NULL) //同样是为了防止L为空集。
            break;
        p = L;
        L = L->next;
        if (L == NULL)
            break;
        if (L->data == m)
        {
            while (1)
            {
                if (L == NULL || L->data != m) //同样运用||的左结合性先判断在运行。
                    break;
                L = L->next;
            }
            p->next = L;
        }
    }
    return head;
}
发布了287 篇原创文章 · 获赞 117 · 访问量 8956

猜你喜欢

转载自blog.csdn.net/qq_44458489/article/details/105376944
今日推荐