实战Leetcode(五)

Practice makes perfect!
在这里插入图片描述

实战一:

在这里插入图片描述

思路:我们要用复制的节点来组成一个新的链表,而原链表的节点随机指向其中一个节点,我们首先给每一个节点都复制并且插入到原来节点的后面,然后用复制的节点指向我们原来节点指向的节点,最后在将复制的节点拿下来尾插到新的链表。
在这里插入图片描述

struct Node* copyRandomList(struct Node* head) {
    struct Node* cur=head;
    while(cur)
    {
        struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
        copy->val=cur->val;

        copy->next=cur->next;
        cur->next=copy;
        cur=cur->next->next;
    }

    cur=head;
    while(cur)
    {
        struct Node* copy=cur->next; 
        if(cur->random==NULL)
        {
            copy->random=NULL;
        }
        else
        {
            copy->random=cur->random->next;

        }
        cur=cur->next->next;
    }

	struct Node* newhead=NULL;
    struct Node* tail=NULL;
    cur=head;
    while(cur)
    {
        struct Node* copy=cur->next;
        struct Node* next=copy->next;
        if(tail==NULL)
        {
            newhead=tail=copy;
        }
        else
        {
           tail->next=copy;
           tail=tail->next;
        }
        cur->next=next;
        cur=next;
    }
    return newhead;

}

实战二:
在这里插入图片描述

思路:这里我们有两个链表,我们将两个链表中小的插到前面形成一个升序的新链表,那么我们首先就要考虑两个链表是否为空,如果链表一为空,那么我们的新链表就是链表二,那么链表二为空,新链表就是链表一,如果都不为空,我们就要比较两个两个链表节点的大小了,小的节点放在前面,如果链表一比链表二小,那么链表一的节点就放在前面,反之则链表二的节点放在前面,如果一个链表为空了,那么我们只要将剩下的那个不为空的链表尾插到新链表的后面就可以了。
在这里插入图片描述

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if(list1==NULL)
    {
        return list2;
    }
    if(list2==NULL)
    {
        return list1;
    }
    struct ListNode* head=NULL;
    struct ListNode* tail=NULL;
    while(list1&&list2)
    {
        if(list1->val<list2->val)
        {
            if(tail==NULL)
            {
                head=tail=list1;
            }
            else
            {
                tail->next=list1;
                tail=tail->next;
            }
            list1=list1->next;
        }
        else
        {
         if(tail==NULL)
         {
             head=tail=list2;
         }
         else
         {
             tail->next=list2;
             tail=tail->next;
         }
         list2=list2->next;
        }
    }
    if(list1)
    {
        tail->next=list1;
    }
    if(list2)
    {
        tail->next=list2;
    }
    return head;
    
}

继续加油,我们下期见!!!

  • 56
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 84
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 84
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lehjy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值