题解 | #牛群分隔#
牛群分隔
https://www.nowcoder.com/practice/16d9dc3de2104fcaa52679ea796e638e
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 lt = new ListNode(-1);
ListNode gt = new ListNode(-1);
ListNode curLt = lt;
ListNode curGt = gt;
while(head != null){
if(head.val < x){
curLt.next = new ListNode(head.val);
curLt = curLt.next;
head = head.next;
}else{
curGt.next = new ListNode(head.val);
curGt = curGt.next;
head = head.next;
}
}
curLt.next = gt.next;
return lt.next;
}
}

查看14道真题和解析