题目:
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.
//思路:开辟两个新链表,将大于x的值放在一个链表上,小于x的值放在一个链表上
贴上AC代码如下:
/**
* 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 head;
ListNode* big=new ListNode(-1);//定义两个新的链表
ListNode* small=new ListNode(-1);
ListNode* bigCur=big;//记录每个新链表的当前末尾的非空节点
ListNode* smallCur=small;
ListNode* p=head;
while(p!=NULL)
{
if(p->val>=x)//添加到大链表中
{
bigCur->next=p;
bigCur=p;
}
else //添加到小链表中
{
smallCur->next=p;
smallCur=p;
}
p=p->next;
}
bigCur->next=NULL;
smallCur->next=big->next;
return small->next;
}
};