LeetCode--partition-list
2017-12-31 20:52
441 查看
题目描述
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,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//构造两个链表,一个大于全部大于等于x,一个全部小于x,然后将两链表合并
class Solution {
public:
// 双指针
ListNode *partition(ListNode *head, int x)
{
ListNode *fake1 = new ListNode(0);
ListNode *fake2 = new ListNode(0);
//构造两个链表的假头结点,起到记录头结点的作用,否则找到合并后的头结点会比较麻烦
ListNode *p1 = fake1,*p2=fake2;
while(head)
{
if(head->val < x)
{
p1->next = head;
p1 = p1->next;
}
else
{
p2->next = head;
p2 = p2->next;
}
head = head->next;
}
p2->next = nullptr;
p1->next = fake2->next;
return fake1->next;
}
};
相关文章推荐
- leetcode之Partition List
- LeetCode Partition List
- (java)leetcode-86:Partition List
- leetcode JAVA Partition List 难度系数3 3.30
- LeetCode Partition List 非常简单易懂的解法
- leetcode — partition-list
- LeetCode Partition List
- LeetCode Partition List
- LeetCode Partition List
- Partition List ---LeetCode
- LeetCode:Partition List
- [LeetCode]Partition List@python
- LeetCode Partition List
- LeetCode Partition List
- partition List Leetcode Python
- LeetCode(Partition List) 划分链表
- leetcode Partition List链表
- Partition List leetcode java
- Leetcode_partition-list
- Partition List ——LeetCode