Partition List

来源:互联网 发布:淘宝代码装修教程 编辑:程序博客网 时间:2024/05/27 18:17

题目描述:

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.

解题思路:

模仿快排的一次排序过程即可。

注:在链表的开头加一个虚拟的节点(dummyHead)可以简化处理过程。


AC代码如下:

class Solution {public:ListNode* partition(ListNode* head, int x) {if (head == NULL) return NULL;ListNode* dummyHead1 = new ListNode(-1);ListNode* p = dummyHead1;ListNode* dummyHead2 = new ListNode(-1);dummyHead2->next = head;ListNode* q = dummyHead2;while (q->next != NULL){if (q->next->val < x){ListNode* tmp = q->next;q->next = tmp->next;p->next = tmp;p = p->next;}else{q = q->next;}}p->next = dummyHead2->next;return dummyHead1->next;}};


0 0
原创粉丝点击