刷题专练之链表(二)


前言

在这里插入图片描述

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

一、合并两个有序链表

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;

    }
};

猜你喜欢

转载自blog.csdn.net/Ruiren_/article/details/129644277