Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
- 类似于快速排序的一部分,只不过由数组变成了链表
- 比数组更简单,直接分成两根链表,一根left记录小于x的点,一根right记录大于等于x的点
- 注意记把right的尾部设为NULL,不然会行程闭环,TLE
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list
* @param x: An integer
* @return: A ListNode
*/
ListNode * partition(ListNode * head, int x) {
ListNode *left_dummy = new ListNode(0);
ListNode *left_tail = left_dummy;
ListNode *right_dummy = new ListNode(0);
ListNode *right_tail = right_dummy;
while (head != NULL) {
if (head->val < x) {
left_tail->next = head;
left_tail = head;
} else {
right_tail->next = head;
right_tail = head;
}
head = head->next;
}
left_tail->next = right_dummy->next;
right_tail->next = NULL;
return left_dummy->next;
}
};