移除链表元素

法一:在原链表上删除

struct SListNode* removeElements(struct SListNode* head, int val)
{
    if (head == NULL)
        return NULL;
    while (head->data == val)
    {
        struct SListNode* del = head;
        head = del->next;
        free(del);
        del = NULL;
        if (head == NULL)
            break;
    }
    if (head == NULL)
        return NULL;
    struct SListNode* cur = head;
    
    while (cur->next != NULL)
    {
        if (cur->next->data == val)
        {
            struct SListNode* del = cur->next;
            cur->next = del->next;
            free(del);
            del = NULL;
        }
        else
        {
            cur = cur->next;
        }
    }
    return head;
}

法二:创建新的链表

struct SListNode* removeElements(struct SListNode* head, int val)
{
    struct SListNode* pcur = NULL, * pend = NULL;
    struct SListNode* cur = head;
    if (cur == NULL)
        return NULL;
    else
    {
        while (cur != NULL)
        {
            if (cur->data != val)
            {
                if (pcur == NULL)
                    pcur = pend = cur;
                else
                {
                    pend->next = cur;
                    pend = cur;
                }
            }
            cur = cur->next;
        }
        if (pend != NULL)
            pend->next = NULL;
        head = pcur;
        return head;
    }
}

相关推荐

  1. 【LeetCode】203. 元素

    2024-04-12 08:22:02       33 阅读
  2. leetcode203. 元素

    2024-04-12 08:22:02       35 阅读
  3. leetcode-元素

    2024-04-12 08:22:02       34 阅读
  4. Leetcode 203 元素

    2024-04-12 08:22:02       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-12 08:22:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-12 08:22:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-12 08:22:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-12 08:22:02       20 阅读

热门阅读

  1. win11 如何把微软账户切换成administrator

    2024-04-12 08:22:02       17 阅读
  2. vue 动态组件、异步组件

    2024-04-12 08:22:02       14 阅读
  3. CSS3进阶技巧:Flexbox布局实战与高级应用

    2024-04-12 08:22:02       16 阅读
  4. element-ui自定义table表头,render-header使用

    2024-04-12 08:22:02       15 阅读
  5. 箭头函数和普通函数的区别

    2024-04-12 08:22:02       13 阅读
  6. Restful API接口规范(以Django为例)

    2024-04-12 08:22:02       13 阅读
  7. CIrcuits--Sequential--Finite_1

    2024-04-12 08:22:02       12 阅读