LCR 029

题目LCR 029


解法一

特殊情况:

  1. 给定链表没有节点,返回新节点
  2. 给定链表只有一个节点,将新节点插入,返回给定节点

一般情况:

  1. 新节点插入列表中间:当cur小于等于新节点,且next大于等于新节点
  2. 新节点插入列表头部:遍历到头尾相连部分时,新节点小于等于头节点,则插入二者之间
  3. 新节点插入列表尾部:遍历到头尾相连部分时,新节点大于等于尾节点,则插入二者之间

注意:当cur大于next时,cur为尾节点,next为头节点

    public Node insert(Node head, int insertVal) {
        Node newNode = new Node(insertVal);
        if (head == null) {
            newNode.next = newNode;
            return newNode;
        }
        if (head.next == head) {
            head.next = newNode;
            newNode.next = head;
            return head;
        }
        Node cur = head, next = cur.next;
        while (next != head) {
            if (cur.val <= insertVal && next.val >= insertVal) break;
            if (cur.val > next.val && (cur.val <= insertVal || next.val >= insertVal)) {
                break;
            }
            cur = next;
            next = next.next;
        }
        cur.next = newNode;
        newNode.next = next;
        return head;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值