您的位置:首页 > 其它

[leetcode] 86. Partition List

2016-08-25 10:12 246 查看
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
.

解法一:

思想都是一样:把小于x的node往前插。

/**
* 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) return head;
ListNode* res = new ListNode(0);
res->next = head;

ListNode* tail = res, *pre = res, *cur = head;
while(cur){
ListNode* next = cur->next;
if(cur->val>=x){
pre = cur;
cur = next;
}else{
if(tail->next!=cur){
cur->next = tail->next;
tail->next = cur;
pre->next = next;
tail = cur;
cur = next;
}else{
tail = cur;
pre = cur;
cur = next;
}
}
}
return res->next;
}
};

解法二:

更简洁一些。主要是多看一位,即判断cur->next->val的大小。

/**
* 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) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
while(pre->next&&pre->next->val<x) pre = pre->next;
ListNode* cur = pre;

while(cur->next){
if(cur->next->val>=x){
cur = cur->next;
}else{
ListNode* next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
pre = pre->next;
}
}
return dummy->next;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode medium