LeetCode刷题笔记 86. 分隔链表

86. 分隔链表

题目要求

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

题解

https://github.com/soulmachine/leetcode

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(!head||!head->next) return head;
        ListNode left_dummy(-1),right_dummy(-1);

        auto left_cur=&left_dummy,right_cur=&right_dummy;
        
        for(ListNode *cur=head;cur;cur=cur->next){
            if(cur->val<x){
                left_cur->next=cur;
                left_cur=cur;
            }
            else{
                right_cur->next=cur;
                right_cur=cur;
            }               
        }
        left_cur->next=right_dummy.next;
        right_cur->next=nullptr;
        return left_dummy.next;
    }
};
发布了18 篇原创文章 · 获赞 0 · 访问量 1800

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/104150171