Leetcode 86. Partition List | | Leetcode 86. Partition List 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/** * 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) { if(!head) { return head; } ListNode* left_head = nullptr; ListNode* right_head = nullptr; ListNode* left = nullptr; ListNode* right = nullptr; ListNode* current = head; while(current) { if(current->val < x) { if(left) { left->next = current; left = left->next; } else { left = current; left_head = left; } } else { if(right) { right->next = current; right = right->next; } else { right = current; right_head = right; } } current = current->next; } if(right) { right->next = nullptr; } if(left) { left->next = right_head; return left_head; } else { return right_head; } }}; Reference https://leetcode.com/problems/partition-list/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏