1、来源: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.
2、
- 题意的意思:将list中小于x的值放到前面,大于等于x放在后面,顺序不变;
- 思路:遍历第一次将小于x的节点组成链表,再遍历一次后将大于等于x的节点加在链表后面;
- 在答案区还有一种思路,就是遍历第一次的时候,建立两个链表,一个链表由小于x的节点组成,一个由大于等于x节点组成,然后合并两个链表即可。
3、代码:
public ListNode partition(ListNode head, int x) {
ListNode resHead = new ListNode(0);
ListNode resCur = resHead;
ListNode cur = head;
while(cur != null){
if(cur.val < x){
resCur.next = new ListNode(cur.val);
resCur = resCur.next;
}
cur = cur.next;
}
cur = head;
while(cur != null){
if(cur.val >= x){
resCur.next = new ListNode(cur.val);
resCur = resCur.next;
}
cur = cur.next;
}
return resHead.next;
}