Partition List
https://leetcode.com/problems/partition-list/description/
Thoughts
Code
/*
* @lc app=leetcode id=86 lang=cpp
*
* [86] Partition List
*/
/**
* 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) {
auto lh = new ListNode(-1), rh = new ListNode(-1), l = lh, r = rh;
while (head != nullptr) {
if (head->val < x) {
l->next = head;
l = l->next;
} else {
r->next = head;
r = r->next;
}
head = head->next;
}
l->next = rh->next;
r->next = nullptr;
return lh->next;
}
};
Analysis
Last updated