题干
partition-list
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小的放在左面,比x大的放在右面,并且保持链表结点的相对位置。
数据结构
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
解题思路
问题一
两种思路,
1.题目没有要求,则可以将原链表拆成两个链表,一个比x小,一个比x大,只需要对链表进行遍历,然后拆分即可。
2.题目如果有in-place这种要求的话不允许开辟新的链表空间,则要用两个指针进行标记,一个为cur为当前讨论的结点,另一个tmp为最后一个小于x的结点的标记,如果cur的val小于x,则插入到tmp之后,后面cur前后两个结点相接。
参考代码
方法一:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(head==NULL)
return head;
ListNode *head1=new ListNode(0),*head2=new ListNode(0);
ListNode *cur1=head1,*cur2=head2;//两个链表头
while(head!=NULL)
{
if(head->val<x)
{
cur1->next=head;
cur1=cur1->next;
}
else
{
cur2->next=head;
cur2=cur2->next;
}
head=head->next;
}
cur2->next=NULL;//拼接链表
cur1->next=head2->next;//这里一定注意把链表2的尾部置为NULL
return head1->next;
}
};
方法二:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(head==NULL)
return head;
ListNode *pre=new ListNode(0);//伪头
pre->next=head;
ListNode *tmp=pre,*cur=pre;
while (cur->next!=NULL)
{
if(cur->next->val<x)//结点的val小于x
{
if(cur==tmp)//这里如果在起点的话要单独讨论,不需要进行结点的插入和删除
{
cur=cur->next;
tmp=tmp->next;
}
else//结点的插入和删除
{
ListNode *p=tmp->next;
tmp->next=cur->next;
cur->next=cur->next->next;
tmp=tmp->next;
tmp->next=p;
}
}
else
cur=cur->next;
}
return pre->next;//返回头部
}
};
方法讨论
方法一没有特殊的,方法二在进行写代码的时候要讨论的结点为cur->next,因为当后面进行删除和拼接的时候如果用当前结点来讨论的话无法找到前面的结点。
易错点
1.方法一链表2的最后要置为NULL.
2.方法二两个标志要开始进行初始化,并且讨论的起始点要单独来确定。