题目:
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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
思路:
这道题目在算法方面的难度也不大,主要是需要维护两个子列表a和b,其中子列表a保存值比x小的所有节点,子列表b保存值不小于x的所有节点。在遍历原始列表时,如果当前节点的值小于x,则将当前节点加入a;否则加入b。最后再将两个子列表合并起来。
对于链表头结点不确定的情况,我们常用的处理技巧就是增加虚拟头结点,方便处理不同情况。但在函数返回之前,一定要记得释放虚拟头结点所占用的内存空间。
代码:
/**
* 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 == NULL || head->next == NULL) {
return head;
}
ListNode *small_head = new ListNode(0); // small nodes
ListNode *small_node = small_head;
ListNode *no_small_head = new ListNode(0); // greater or equal nodes
ListNode *no_small_node = no_small_head;
ListNode *node = head;
while(node) {
if(node->val < x) {
small_node->next = node;
small_node = small_node->next;
}
else{
no_small_node->next = node;
no_small_node = no_small_node->next;
}
node = node->next;
}
no_small_node->next = NULL; // connect two parts together
small_node->next = no_small_head->next;
head = small_head->next;
delete small_head, no_small_head;
return head;
}
};