leetcode 链表 Partition List
2014-10-12 00:15
519 查看
Partition List
Total Accepted: 19761 TotalSubmissions: 73252My Submissions
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->2and x = 3,
return
1->2->2->4->3->5.
题意:根据给定值x划分链表,使得比x小的值排在前面。要求保持元素原先的相对位置。
思路:
维护两个链表,一个是比x小的节点的链表l1,另一个是大于等于x的节点的链表l2
最后把l1的尾部接到l2的头部
复杂度:时间O(n),空间O(1)
ListNode *partition(ListNode *head, int x) {
ListNode less(-1), larger_equal(-1);
ListNode *less_ptr = &less, *larger_equal_ptr = &larger_equal;
for (ListNode *cur = head; cur != NULL; cur = cur->next)
{
if(cur->val < x){
less_ptr = less_ptr->next = cur;
}else{
larger_equal_ptr = larger_equal_ptr->next = cur;
}
}
less_ptr->next = larger_equal.next;
larger_equal_ptr->next = NULL;
return less.next;
}
相关文章推荐
- LeetCode 86 Partition List (链表)
- [Leetcode] Partition list 划分链表
- [LeetCode] Partition List(!!!!巧妙的链表插入)
- LeetCode之“链表”:Partition List
- LeetCode | Partition List(partition方法处理链表)
- Partition List 分类: Leetcode(链表) 2015-03-03 21:13 29人阅读 评论(0) 收藏
- 【leetcode】【单链表】【86】Partition List
- LeetCode-86-Partition List(链表)-Medium
- 【leetcode】【单链表】【86】Partition List
- LeetCode-86-Partition List 链表
- 【LeetCode】Partition List 链表划分 - Easy +
- [LeetCode] Partition List 划分链表
- Partition List 链表划分区间@LeetCode
- 【LeetCode】Partition List ——链表排序问题
- leetcode 链表 Partition List
- LeetCode-Partition List-分割链表-链表操作
- [LeetCode-86] Partition List (链表数据分区)
- Leetcode033--单链表中去除重复的元素
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- Leetcode Remove Duplicates from Sorted List 删除链表中的重复元素