继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

将单向链表按某值划分成左边小、中间相等、右边大的形式

holdtom
关注TA
已关注
手记 1703
粉丝 240
获赞 991


class Solution {

    private static ListNode[] getArray(ListNode head) {

        if (head == null) {

            return new ListNode[0];

        }

        int size = 0;

        ListNode p = head;

        while (p != null) {

            ++ size;

            p = p.next;

        }

        ListNode[] result = new ListNode[size];

        p = head;

        size = 0;

        while (p != null) {

            result[size ++] = p;

            p = p.next;

        }

        return result;

    }

    private static ListNode getList(ListNode[] array) {

        if (array == null || array.length == 0) {

            return null;

        }

        ListNode head = array[0];

        ListNode pre = head;

        for (int i = 1;i < array.length; ++ i) {

            pre.next = array[i];

            pre = array[i];

        }

        pre.next = null;

        return head;

    }

    private static void swap(ListNode[] array, int a, int b) {

        if (a == b) {

            return;

        }

        ListNode t = array[a];

        array[a] = array[b];

        array[b] = t;

    }

    private static ListNode function(ListNode head, int val) {

        ListNode[] array = getArray(head);

        int size = array.length;

        int l = -1;

        int r = size - 1;

        int i = 0;

        while (i <= r) {

            if (array[i].val < val) {

                swap(array, ++ l, i ++);

            } else if (array[i].val == val) {

                ++ i;

            } else {

                swap(array, i, r --);

            }

        }

        return getList(array);

    }

    private static void print(ListNode head) {

        while (head != null) {

            System.out.println(head.val);

            head = head.next;

        }

    }

    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; }

}

©著作权归作者所有:来自51CTO博客作者天一涯51CTO的原创作品,如需转载,请注明出处,否则将追究法律责任


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP