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->2
and x = 3,
return 1->2->2->4->3->5
.
意思是给你一个链表和一个数x,把比x数小的数都放在前面,大于等于x的数在后面,顺序是不能乱的。
比入example中的1,2,2比三小,所以在最前面,435大于等于3所以在后面,最后就是1->2->2->4->3->5;
最直接的就是用两个链表,一个存比三小的,一个存比三大的,然后拼起来。
/**
* 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 == NULL) return NULL;
ListNode* l1 = NULL, *l2 = NULL, *l1now = NULL, *l1next = NULL, *l2now = NULL, *l2next = NULL;
while (head)
{
if (head->val<x)
{
l1next = new ListNode(head->val);
if (l1==NULL)
{
l1 = l1now = l1next;
}
else
{
l1now->next = l1next;
l1now = l1next;
}
}
else
{
l2next = new ListNode(head->val);
if (l2 == NULL)
{
l2 = l2now = l2next;
}
else
{
l2now->next = l2next;
l2now = l2next;
}
}
head = head->next;
}
if (l1)
{
if (l2)
{
l1now->next = l2;
}
return l1;
}
else
{
return l2;
}
}
};
链表就暂时做这些了,medium的还有两个排序的没有做,等再复习下排序算法后再来做吧。