LeetCode题解:Partition List
2013-11-07 04:30
357 查看
Partition List
Given a linked list and a value x, partition it such that all nodes less thanx 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->2and x = 3,
return
1->2->2->4->3->5.
思路:
遍历整个链表,把大于等于x的和小于x的数据分别放在两个不同链表中,然后再将它们连接起来。
题解:
/** * 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 == nullptr) return nullptr; ListNode* larger_head = new ListNode(0); ListNode* larger_last = larger_head; ListNode* less_head = new ListNode(0); ListNode* less_last = less_head; auto push = [](ListNode*& last, ListNode* new_less) { last->next = new_less; last = last->next; last->next = nullptr; }; ListNode* iter = head; while(iter != nullptr) { ListNode* next = iter->next; if (iter->val < x) push(less_last, iter); else push(larger_last, iter); iter = next; } // merge two lists if (less_last != less_head) { // less is not empty less_last->next = larger_head->next; delete larger_head; less_last = less_head->next; delete less_head; return less_last; } else { // less is empty delete less_head; larger_last = larger_head; larger_head = larger_head->next; delete larger_last; return larger_head; } } };
相关文章推荐
- LeetCode题解-86-Partition List
- [LeetCode]题解(python):086-Partition List
- LeetCode-Partition List
- leetcode 题解 || Search for a Range 问题
- leetcode_题解_path sum_easy
- leetcode题解-149. Max Points on a Line
- [LeetCode]Partition List
- leetcode:Partition List
- leetcode-Two Sum[题解]
- 【LeetCode】Partition List 解题报告
- [leetcode] Partition List
- leetcode 题解代码整理 26-30题
- leetcode: Partition List
- LeetCode - 3Sum 题解
- leetcode题解
- leetcode 题解:Remove Duplicates from Sorted Array II(已排序数组去三次及以上重复元素)
- leetcode_效率题解_148. Sort List_(链表归并排序)
- Partition List 链表划分区间@LeetCode
- leetcode题解-binary search题目总结
- Leetcode题解-33. Search in Rotated Sorted Array