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
// 1. 处理特殊情况
if (head == null || head.next == null) return head;
// 2, 定义两端链表的头尾指针
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
// 3. 开始循环遍历链表进行处理
while (head != null) {
// 3.1 如果当前节点的值小于x
if (head.val < x) {
// 3.1.1 就采用尾插法将元素插入前一段链表中
if (bs == null) {
bs = head;
be = head;
} else {
be.next = head;
be = be.next;
}
} else {
// 3.2 如果当前节点的值大于等于x就采用尾插法插入后半段链表
if (as == null) {
as = head;
ae = head;
} else {
ae.next = head;
ae = ae.next;
}
}
head = head.next;
}
// 4. 处理特殊情况:如果前半段为空直接返回
if (bs == null) return as;
be.next = as; // 此处前半段不为空,将前后两段连接
ae.next = null; // 最后置空最后一个链表节点防止循环链表产生
// 5. 返回
return bs;
}
}