剑指 Offer II 029. 排序的循环链表

[题目链接](剑指 Offer II 029. 排序的循环链表 - 力扣(LeetCode) (leetcode-cn.com))

思路

  • 特殊情况:插入链表节点数小于2
  • 一般情况:1.插入节点大于或者小于插入链表中的所有节点,此时将插入节点插入到最大节点与最小节点之间;2.插入节点介于插入链表两个节点(除了最大节点与最小节点之间)之间,找到这两个节点,直接进行插入。

代码

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

class Solution {
    public Node insert(Node head, int insertVal) {
        Node node = new Node(insertVal);
        if(head == null) {//插入链表为空的情况
            head = node;
            node.next = head;
        } else if(head.next ==  null) {//插入链表只有一个节点的情况
            head.next = node;
            node.next = head;
        } else {
            insertNode(head,insertVal);
        }
        return head;
    }
    private void insertNode(Node head, int insertVal) {
        Node node = new Node(insertVal);
        Node cur = head;
        Node next = cur.next;
        Node biggest = cur;
        while(!(cur.val <= node.val && node.val <= next.val) && next != head) {
            //找到插入节点在两个节点之间的两个节点
            //next != head 是否防止插入节点在最大节点与最小节点之间,此时防止死循环
            cur = next;
            next = cur.next;
            if(cur.val >= biggest.val) biggest = cur;//找到值最大的节点
        }
        if(cur.val <= node.val && node.val <= next.val) {
            cur.next = node;
            node.next = next;
        } else {
            node.next = biggest.next;
            biggest.next = node;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值