题解 | #划分链表#

划分链表

https://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f

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 partition (ListNode pHead, int x) {
        // write code here
        if (pHead == null || pHead.next == null){
            return pHead;
        }
        ListNode minXF = null;
        ListNode minXE = null;
        ListNode maxXF = null;
        ListNode maxXE = null;
        while (pHead != null) {
            if (pHead.val < x) {
                if (minXF == null) {
                    minXE = pHead;
                    minXF = pHead;
                }else {
                    minXE.next = pHead;
                    minXE = pHead;
                }
            }else {
                if (maxXF == null) {
                    maxXE = pHead;
                    maxXF = pHead;
                }else {
                    maxXE.next = pHead;
                    maxXE = pHead;
                }
            }
            pHead = pHead.next;
        }
        if (minXF != null){
            minXE.next = maxXF;
        }
        if (maxXE != null) {
            maxXE.next = null;
        }
        if (minXF == null){
            return maxXF;
        }
        return minXF;
    
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务