【C++】链表根据数值划分算法

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你应当保留两个分区中每个节点的初始相对位置。

  • 弄两个新的表头,一个储存小于特定值的节点,一个储存大于特定值的结点,再结合,简单的直接上代码:
    结点数据结构:
 // Definition for singly-linked list.
struct ListNode {
    
    
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {
    
    }
};

解决:

class Solution {
    
    
public:
    ListNode* partition(ListNode* head, int x) {
    
    
        ListNode less_head(0);
        ListNode more_head(0);
        ListNode* less_ptr = &less_head;
        ListNode* more_ptr = &more_head;
        while (head)
        {
    
    
            if (head->val < x) {
    
    
                less_ptr->next = head;
                less_ptr = head;
            }
            else
            {
    
    
                more_ptr->next = head;
                more_ptr = head;
            }
            head = head->next;
        }
        less_ptr->next = more_head.next;
        more_ptr->next = NULL;
        return less_head.next;
    }
    
};

ps: 小象学院教程 https://www.bilibili.com/video/BV1GW411Q77S?t=7029&p=2 的笔记
LeetCode题号: 86

猜你喜欢

转载自blog.csdn.net/weixin_44427114/article/details/107868141