Leetcode 86. Partition List
2018-10-14 本文已影响0人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
![](https://img.haomeiwen.com/i3232548/bd7ed6e8a53b647e.png)
2. Solution
/**
* 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;
}
}
};