LeetCode: Partition List
2014-09-01 22:16
483 查看
[b]LeetCode: Partition List[/b]
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
return
地址:https://oj.leetcode.com/problems/partition-list/
算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:
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.
地址:https://oj.leetcode.com/problems/partition-list/
算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:
/** * 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 NULL; ListNode *p = head; ListNode *pre = NULL; while(p && p->val < x){ pre = p; p = p->next; } if(!p) return head; ListNode *q = NULL; while(p->next){ if(p->next->val < x){ q = p->next; p->next = q->next; if(pre){ q->next = pre->next; pre->next = q; pre = q; }else{ q->next = head; head = q; pre = q; } }else{ p = p->next; } } return head; } };
相关文章推荐
- LeetCode: Partition List
- LeetCode086 Partition List
- 【LeetCode】Partition List
- LeetCode 之 Partition List — C++ 实现
- [LeetCode]Partition List
- leetCode(10):Partition List 分类: leetCode 2015-06-18 09:08 105人阅读 评论(0) 收藏
- LeetCode Online Judge 题目C# 练习 - Partition List
- leetcode之Partition List
- leetcode 【 Partition List 】python 实现
- 086 Partition List [Leetcode]
- leetcode-- Partition List
- 【leetcode】Partition List
- Leetcode - Partition List.
- Leetcode: Partition List
- [leetcode]Partition List
- LeetCode 86 Partition List
- Partition List 分类: Leetcode(链表) 2015-03-03 21:13 29人阅读 评论(0) 收藏
- 【LeetCode】Partition List
- [LeetCode63]Partition List
- leetCode(10):Partition List