import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
public ListNode cow_partition (ListNode head, int x) {
// write code here
ListNode small = new ListNode(0), big = new ListNode(0), sp = small, bp = big, cur = head;
while (cur != null) {
if (cur.val < x) {
sp.next = cur;
sp = sp.next;
} else {
bp.next = cur;
bp = bp.next;
}
cur = cur.next;
}
bp.next = null;
sp.next = big.next;
return small.next;
}
}
- 分别定义一小一大两个哨兵节点small、big,以及指向这两个哨兵节点的指针 sp、bp,用于遍历原链表的指针 cur
- 借助 cur、sp、bp 将原链表分隔成一小一大两部分
- 最后将节点值较小的链表和节点值较大的链表连接起来
- 返回结果 small.next
