您的位置:首页 > 其它

将单向链表按某值划分成左边小、中间相等、右边大的形式(O(1)空间复杂度,稳定划分)

2018-12-23 23:53 686 查看
class Solution {

    private static ListNode function(ListNode head, int val) {
        ListNode left = new ListNode(0);
        ListNode mid = new ListNode(0);
        ListNode right = new ListNode(0);
        ListNode tail1 = null, tail2 = null, tail3 = null;
        ListNode next;
        ListNode cur = head;
        while (cur != null) {
            next = cur.next;
            if (cur.val < val) {
                append(left, tail1, cur);
                tail1 = cur;
            } else if (cur.val == val) {
                append(mid, tail2, cur);
                tail2 = cur;
            } else {
                append(right, tail3, cur);
                tail3 = cur;
            }
            cur = next;
        }
        return merge(left.next, tail1, mid.next, tail2, right.next, tail3);

    }

    private static void print(ListNode head) {
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    public static void append(ListNode list, ListNode tail, ListNode node) {
        if (list == null) {
            return;
        }
        if (tail != null) {
            tail.next = node;
        } else {
            list.next = node;
        }
        node.next = null;
    }

    public static ListNode merge(ListNode l1, ListNode tail1,
                                 ListNode l2, ListNode tail2,
       &nb
5b4
sp;                         ListNode l3, ListNode tail3) {
        ListNode head;
        // find head
        if (l1 != null) {
            head = l1;
        } else if (l2 != null) {
            head = l2;
        } else {
            head = l3;
        }
        if (tail1 != null) {
            tail1.next = l2;
        }
        if (tail2 != null) {
            tail2.next = l3;
        } else if (tail1 != null) {

2d9a
            tail1.next = l3;
        }
        tail3.next = null;
        return head;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(9);
        ListNode n2 = new ListNode(0);
        ListNode n3 = new ListNode(4);
        ListNode n4 = new ListNode(5);
        ListNode n5 = new ListNode(1);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;

        ListNode head = function(n1, 3);

        print(head);

    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 partition
相关文章推荐