题解 | #牛的品种排序IV#
牛的品种排序IV
https://www.nowcoder.com/practice/bd828af269cd493c86cc915389b02b9f
知识点
链表,链表拼接
解题思路
遍历链表,将0的节点放在一个链表,将1的节点放在另一个链表。
遍历结束后,将0的链表next指向1的链表。
这其中要注意1的链表之后要把next设置为null。
Java题解
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode sortCowsIV (ListNode head) { // write code here ListNode black = new ListNode(0); ListNode blackP = black; ListNode white = new ListNode(0); ListNode whiteP = white; while(head != null) { if(head.val == 0){ black.next = head; black = black.next; } else { white.next = head; white = white.next; } head = head.next; } white.next = null; black.next = whiteP.next; return blackP.next; } }