排序的循环链表之问题分析归类整理

排序的循环链表之问题分析

前言

当问题杂乱时,可以分类整理,把情况理清楚。

一、案例

在这里插入图片描述

二、题解

package com.xhu.offer.offerII;

//排序的循环链表
public class Insert {
    //总结:该题考查问题分析拆解并归类。训练分情况讨论。
    //总结:有时候用循环需要先提前写一个循环体在外面,导致很不方便,可以用do  while去替代。
    public Node insert(Node head, int insertVal) {
        if (head == null) {
            Node root = new Node(insertVal);
            root.next = root;
            return root;
        }
        Node res = head;
        //遍历找到比它小的节点,或者是下一个节点小于上一个节点值。
        //1,只有两种情况可以插入节点,否则都是往后移继续寻找可以插入处。
        //第一,节点值在前后节点之间,节点值在头尾之间;
        do {
            int m = head.val, n = head.next.val;

            if (m <= n && insertVal >= m && insertVal <= n) {
                Node node = new Node(insertVal);
                node.next = head.next;
                head.next = node;
                return res;
            }
            if (m > n && (insertVal >= m || insertVal <= n)) {
                Node node = new Node(insertVal);
                node.next = head.next;
                head.next = node;
                return res;
            }
            head = head.next;
        } while (res != head);
        Node node = new Node(insertVal);
        node.next = res.next;
        res.next = node;
        return node.next;
    }

    // Definition for a Node.
    class Node {
        public int val;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _next) {
            val = _val;
            next = _next;
        }
    }
}

总结

1)该题考查问题分析拆解并归类。训练分情况讨论。
2)有时候用循环需要先提前写一个循环体在外面,导致很不方便,可以用do while去替代。

参考文献

[1] LeetCode 原题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值