[LeetCode] 203.移除链表元素, 21.合并两个有序链表

1.移除链表元素

题目描述

删除链表中等于给定值 val 的所有节点。

示例1:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

使用语言: C语言

思路解析

遍历找出所有不是val的节点,尾插到新链表上,等于val的节点尾插到新链表上,不等于val的节点直接free掉

图解如下:
在这里插入图片描述

代码实现

struct ListNode* removeElements(struct ListNode* head, int val)
{
    
    
    //如果是空链表
    if(head == NULL)
    {
    
    
        return head;
    }
    struct ListNode* cur = head;
    //相当于一个头指针
    struct ListNode* newhead = NULL;
    //相当于一个尾指针,用于找下一个位置
    struct ListNode* tail = NULL;
    while(cur)
    {
    
    
        //保存下一个节点
         struct ListNode* next = cur->next;
         //当值不等于val,放入newhead
         if(cur->val != val)
         {
    
    
             //判断新空间newhead是否为空
             if(newhead == NULL)
             {
    
    
                 newhead = tail = cur;
             }
             else
             {
    
    
                 tail->next = cur;
                 tail = cur;
             }
         }
         //若cur->val等于cur直接释放掉
         else
         {
    
    
             free(cur);
         }
         cur = next;
    }
    //处理尾
    if(tail)
      tail->next = NULL;
    return newhead;
}

2.合并两个有序链表

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例1
在这里插入图片描述
使用语言: C语言

思路解析

此题的思路和移除链表元素思路相似,在两个链表上取小的节点,尾插到新链表上(特殊情况:如果一个链表为空,则返回另一个链表,)

图解如下:
在这里插入图片描述

代码实现:

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
    
    
    //l1为空返回l2
    if(l1 == NULL)
    {
    
    
        return l2;
    }
    //l2为空返回l1
    if(l2 == NULL)
    {
    
    
        return l1;
    }
    //头指针
    struct ListNode* head = NULL;
    //尾指针
    struct ListNode* tail = NULL;
    //取两个链表中小的节点放入新链表中
    while(l1 && l2)
    {
    
    
        if(l1->val < l2->val)
        {
    
    
            if(head == NULL)
            {
    
    
                head = tail = l1;
            }
            else
            {
    
    
                tail->next = l1;
                tail = l1;
            }
            l1 = l1->next;
        }
        else
        {
    
    
            if(head == NULL)
            {
    
    
                head = tail = l2;
            }
            else
            {
    
    
                tail->next = l2;
                tail = l2;
            }
            l2 = l2->next;
        }
    }
    //l2先结束,l1未结束
    if(l1)
    {
    
    
        tail->next = l1;
    }
    //l1先结束,l2未结束
    if(l2)
    {
    
    
        tail->next = l2;
    }
    return head;
}

猜你喜欢

转载自blog.csdn.net/weixin_50886514/article/details/113400183