Partition List
Description
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.
You should preserve the original relative order of the nodes in each of the two partitions.
Example Given 1->4->3->2->5->2->null and x = 3, return 1->2->2->4->3->5->null.
Link
Method
- create two dummy lists, then trying to append them
- x
Example
- 1
/** * Definition of ListNode * 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) { // write your code here if (!head) { return nullptr; } ListNode dummy1(INT_MIN); ListNode dummy2(INT_MIN); ListNode* less_head = &dummy1; ListNode* more_head = &dummy2; ListNode* less = &dummy1; ListNode* more = &dummy2; ListNode* cur = head; while (cur) { if (cur->val < x) { less->next = new ListNode(cur->val); less = less->next; } else { more->next = new ListNode(cur->val); more = more->next; } cur = cur->next; } less->next = more_head->next; return less_head->next; } };
Similar problems
x
Tags
x