微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

链表 - 将大于某一个值的节点全部放在右边、小于该值的放在左边

public static Node leftRightListNode (Node head, int target) {
        Node small = null;
        Node big = null;
        Node l1 = null;
        Node l2 = null;
        //1、遍历节点

        for (Node cur = head; cur != null ; cur=cur.next) {
            if (cur.val < target) {
                if (small == null) {
                    small = cur;
                } else {
                    l1.next = cur;
                }
                //2、保存小于该值的节点链
                l1 = cur;
            } else {
                if (big == null) {
                    big = cur;
                } else {
                    l2.next = cur;
                }
                //3、保存大于该值的节点链
                l2 = cur;
            }
        }
        //4、如果小于的节点链不存在,直接返回大于链表
        if (small == null) {
            return big;
        } else {
            //5、否则将小于该值的节点链的next置为大于该值的节点链
            small.next = big;
        }
        return small;
    }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐