刷题专练之链表(二)


前言

在这里插入图片描述

书接上回,此篇依然是链表专题

一、合并两个有序链表

1.题目介绍

题目在力扣21. 合并两个有序链表
在这里插入图片描述

2.思路

我们将两个链表的val相互比较,将小的数据链接到新的链表后后面,然后向后迭代

1️⃣
在这里插入图片描述
2️⃣
在这里插入图片描述
3️⃣
在这里插入图片描述
4️⃣
在这里插入图片描述
5️⃣
在这里插入图片描述
6️⃣
在这里插入图片描述
6️⃣
在这里插入图片描述

3.代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
        struct ListNode* dummyNode,*tail=NULL;
        tail=dummyNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        dummyNode->next=NULL;
        struct ListNode*cur1=list1,*cur2=list2;
        while(cur1&&cur2)
        {
            if(cur1->val>cur2->val)
            {
               tail->next=cur2;
               cur2=cur2->next;
               tail=tail->next;   
            }
            else
            {
                tail->next=cur1;
                cur1=cur1->next;
                tail=tail->next;
            }
        }
        if(cur1)
        {
            tail->next=cur1;
        }
        if(cur2)
        {
            tail->next=cur2;
        }
        struct ListNode* temp=dummyNode->next;
        free(dummyNode);
        return  temp;
}

二、链表分割

1.题目介绍

题目在牛客链表分割
在这里插入图片描述

2.思路

当你上面一题做懂了之后,你就会发现这题迎刃而解,只是条件换成了小于x而已

3.代码

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
       struct ListNode *smallhead,*smalltail;
       struct ListNode *bighead,*bigtail;
       smallhead=smalltail=(struct ListNode*)malloc(sizeof(struct ListNode));
       bighead=bigtail=(struct ListNode*)malloc(sizeof(struct ListNode));
       smalltail->next=NULL;
       bigtail->next=NULL;
       struct ListNode *cur=pHead;
       while(cur)
       {
        if(cur->val<x)
        {
            smalltail->next=cur;
            smalltail=smalltail->next;
        }
        else
        {
            bigtail->next=cur;
            bigtail=bigtail->next;
        }
        cur=cur->next;
       }
       smalltail->next=bighead->next;
       bigtail->next=NULL;
       pHead=smallhead->next;
        free(bighead);
        free(smallhead);
       return pHead;

    }
};
  • 20
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ruiren.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值