[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; } } };
相关文章推荐
- [leetcode]Partition List
- leetcode 日经贴,Cpp code -Partition List
- LeetCode 86: Partition List
- LeetCode - Partition List
- 【leetcode】Partition List(middle)
- [C语言][LeetCode][86]Partition List
- leetCode(10):Partition List
- LeetCode-Partition List
- Leetcode 86 Partition List
- LeetCode-Partition List
- LeetCode 86 Partition List
- [LeetCode] Partition List
- LeetCode - 86 - Partition List
- Leetcode:Partition List
- leetcode笔记--Partition List
- [leetcode] Partition List
- 【LeetCode】Partition List 解题报告
- [LeetCode] Partition List
- Leetcode_86_Partition List
- [leetcode刷题系列]Partition List