题意
将小于x的结点插到大于等于x的数之前
题解
如题
代码
java version:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null)
return null;
ListNode vhead = new ListNode(0);
vhead.next= head;
ListNode iter = vhead;
while(iter.next != null && iter.next.val < x)
iter = iter.next;
ListNode prev = iter; // last node that less than x
while(iter.next != null)
{
if(iter.next.val < x)
{
ListNode insertNode = iter.next; // remember inserNode
// delete node from back linked-list
iter.next = iter.next.next;
//insert node in front linked-list
insertNode.next = prev.next;
prev.next = insertNode;
//prev point to insert position
prev = prev.next;
}
else
iter = iter.next;
}
return vhead.next;
}
}