您的位置:首页 > 其它

[LeetCode]Partition List

2013-05-30 10:27 351 查看
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode *partition(ListNode *head, int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* p = head;
ListNode* smallerNow = NULL;
ListNode* smallerHead = NULL;
ListNode* greaterNow = NULL;
ListNode* greaterHead = NULL;
while (p)
{
if(p->val < x)
{
if(!smallerHead) smallerNow = smallerHead = p;
else smallerNow->next = p, smallerNow = p;
}
else
{
if(!greaterHead) greaterNow = greaterHead = p;
else  greaterNow->next = p, greaterNow = p;
}
p = p->next;
}
if(greaterHead) greaterNow->next = NULL;
if(smallerHead) smallerNow->next = NULL;
if(!smallerHead && !greaterHead) return NULL;
else if(!smallerHead) return greaterHead;
else
{
smallerNow->next = greaterHead;
return smallerHead;
}
}
};

second time

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode dummy1(-1);
ListNode dummy2(-1);
ListNode* prev1 = &dummy1;
ListNode* prev2 = &dummy2;
ListNode* cur = head;
while(cur != NULL)
{
if(cur->val < x)
{
prev1->next = cur;
prev1 = prev1->next;
}
else
{
prev2->next = cur;
prev2 = prev2->next;
}
cur = cur->next;
}
prev1->next = NULL;
prev2->next = NULL;
if(dummy1.next == NULL) return dummy2.next;
else
{
prev1->next = dummy2.next;
return dummy1.next;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: