其他分享
首页 > 其他分享> > 链表 - 将大于某一个值的节点全部放在右边、小于该值的放在左边

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

作者:互联网

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

 

标签:Node,放在,cur,next,链表,该值,small,null,节点
来源: https://www.cnblogs.com/slidecode/p/16033312.html