题解 | #牛群分隔#
牛群分隔
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
if (head == null || head.next == null)
return head;
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode p1=dummy1;
ListNode p2=dummy2;
while (head != null) {
if(head.val < x) {
p1.next = head;
p1 = p1.next;
head=head.next;
p1.next=null;
}else{
p2.next = head;
p2 = p2.next;
head=head.next;
p2.next=null;
}
}
p1.next = dummy2.next;
return dummy1.next;
}
}
