题解 | 牛的品种排序IV
牛的品种排序IV
https://www.nowcoder.com/practice/bd828af269cd493c86cc915389b02b9f
- 参考牛群分隔即可。
import java.util.*; public class Solution { public ListNode sortCowsIV (ListNode head) { if (head == null || head.next == null) { return head; } ListNode black = new ListNode(0); ListNode bTail = black; ListNode white = new ListNode(1); ListNode wTail = white; while (head != null) { if (head.val == 0) { bTail.next = head; bTail = bTail.next; } else { wTail.next = head; wTail = wTail.next; } head = head.next; } wTail.next = null; bTail.next = white.next; return black.next; } }