• 《程序员代码面试指南》第二章 链表问题 将单链表按某值划分为左边小,中间相等,右边大的链表


    题目

    例如 链表 1-2-3-6-7-8-5-4-9-10 ,按 5分为左边小,中间相等,右边大的链表,1-2-3-4-5-6-7-8-9-10
    

    java代码

    /**
     * @Description:将单链表按某值划分为左边小,中间相等,右边大的链表
     * @Author: lizhouwei
     * @CreateDate: 2018/4/6 21:26
     * @Modify by:
     * @ModifyDate:
    */
    public class Chapter2_8 {
        public Node partition(Node head, int pivot) {
            if (head == null) {
                return null;
            }
            Node sH = null;//小的链表的头节点
            Node sT = null;//小的链表的尾节点
            Node eH = null;//相等的链表的头节点
            Node eT = null;//相等的链表的头节点
            Node bH = null;//大的链表的头节点
            Node bT = null;//大的链表的尾节点
            Node next = null;
            while (head != null) {
                next = head.next;
                head.next = null;
                if (head.vlaue < pivot) {
                    if (sH == null) {
                        sH = head;
                        sT = head;
                    } else {
                        sT.next = head;
                        sT = head;
                    }
                } else if (head.vlaue == pivot) {
                    if (eH == null) {
                        eH = head;
                        eT = head;
                    } else {
                        eT.next = head;
                        eT = head;
                    }
                } else {
                    if (bH == null) {
                        bH = head;
                        bT = head;
                    } else {
                        bT.next = head;
                        bT = head;
                    }
                }
                head = next;
            }
            //重新连接
            if (sT != null) {
                sT.next = eH;
                eT = eT == null ? sT : eT;
            }
            if (eT != null) {
                eT.next = bH;
            }
            return sH != null ? sH : eH != null ? eH : bH;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_8 chapter = new Chapter2_8();
            Link link = new Link();
            //构造两个链表
            for (int i = 10; i > 0; i--) {
                link.add(i);
                link.add(i + 10);
            }
            Link.printLink(link.head);
            Node head = chapter.partition(link.head, 10);
            Link.printLink(head);
        }
    }
    
  • 相关阅读:
    Jenkins常见的构建触发器
    NTP服务器搭建
    Jenkins钉钉通知
    Jenkins邮件通知
    升级到k8s的17.0出现问题
    推荐K8s的一键安装和一键升级
    Pipeline流水线项目构建
    Jenkins构建Maven项目
    Jenkins构建自由风格的项目
    Codeforces Round #570 (Div. 3 )A
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8729056.html
Copyright © 2020-2023  润新知