左神算法笔记-分隔链表

50 阅读1分钟
public ListNode partition(ListNode head, int x) {
    ListNode temp = null;
    // 定义大头、大尾,存放
    ListNode bigHead = null, bigTail = null;
    // 定义小头,小尾
    ListNode smallHead = null, smallTail = null;
    while (head != null) {
        // 1,4,3,2,5,2   x = 3
        // 临时变量,存储下一个节点
        temp = head.next;
        head.next = null;
        if (head.val < x) {
            // <x挂小头、小尾
            if (smallHead == null) {
                smallHead = head;
            } else {
                smallTail.next = head;
            }
            smallTail = head;
        } else {
            // >=x挂大头、大尾
            if (bigHead == null) {
                bigHead = head;
            } else {
                bigTail.next = head;
            }
            bigTail = head;
        }
        head = temp;
    }
    // 不存在大于等于x的数据,直接返回大头,否则将大头挂到小头尾部返回
    if (smallHead == null) {
        return bigHead;
    }
    smallTail.next = bigHead;
    return smallHead;
}