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
.
Input:
[2,1]
3
Expected:
[2,1]
Input:
[2,1,3]
3
Expected:
[2,1,3]
Input:
[3,1]
2
Expected:
[1,3]
Input:
[1]
2
Expected:
[1]
Input:
[2,3,1]
3
Expected:
[2,1,3]
input
[4,7,1,1,1,1]
7
Expected answer
[4,1,1,1,1,7]
input
[2,4,7,1,1,1,1,3]
7
Expected answer
[2,4,1,1,1,1,3,7]
刚开始没有理解题目意思,把小于x的节点删除然后插入到前面,吃好多WA,顾名思义 “切分” ,用两个链表,
遍历一边原来的链表,分表保存节点值小于x的节点和值大于等于x的节点,最后把小的放在前面,后面接上大的即可。
这样也保持了原顺序。
刚开始写了一个空间O(N)版本的
public ListNode partition(ListNode head, int x)
{
ListNode lesshead=new ListNode(-1);
ListNode greaterhead=new ListNode(-1);
ListNode less=lesshead;
ListNode greater=greaterhead;
ListNode p=head;
while(p!=null)
{
if(p.val<x)
{
less.next=new ListNode(p.val);
less=less.next;
}
else {
greater.next=new ListNode(p.val);
greater=greater.next;
}
p=p.next;
}
less.next=greaterhead.next;
return lesshead.next;
}
后来觉得这样的答案不是理想的,还是使用O(1)空间重写一个吧,依然两个表,一个小于的表一个大于等于表,每次保存当前节点的后继,把当前节点的next置null以后根据节点值与x的大小关系决定挂在哪一边,挂完了之后取保存的后继继续遍历。两个表都挂完之后把greater表挂在less表尾就行了。
public ListNode partition(ListNode head, int x)
{
ListNode less=new ListNode(-1);
ListNode greater=new ListNode(-1);
ListNode p=head;
ListNode pnext=null;
ListNode pless=less;
ListNode pgreater=greater;
while(p!=null)
{
pnext=p.next;
p.next=null;
if(p.val<x)
{
pless.next=p;
pless=pless.next;
}
else {
pgreater.next=p;
pgreater=pgreater.next;
}
p=pnext;
}
pless.next=greater.next;
return less.next;
}