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

剑指 Offer II 029. 排序的循环链表
思路:
    主要是考虑插入情况,如果插入的数在两个数中间,就直接插入,如果没有这种情况,那么这个数一定是大于最大值或者小于最小值的情况下,那么它一定是插入最大最小值节点中间的。当然第一步要找到最大值的节点。
    其次考虑边界情况,如果整个链表中没有一个节点,那么直接插入,next指向自己。如果链表中只有一个节点,那么插入后互相连接就行了。

class Solution {
public:
    Node* insert(Node* head, int insertVal) 
    {
        Node* node = new Node(insertVal);
        if (head == nullptr)
        {
            head = node;
            node->next = head;
        }
        if (head->next == nullptr)
        {
            head->next = node;
            node->next = head;
        }
        else
        {
            insertCore(head, node);
        }
        return head;
    }

    void insertCore(Node* head, Node* node)
    {
        Node* cur = head;
        Node* next = head->next;
        Node* biggest = head;
        while (!(cur->val <= node->val && next->val >= node->val) && next != head)
        {
            cur = next;
            next = next->next;
            if (cur->val >= biggest->val)
                biggest = cur;
        }

        if (cur->val <= node->val && next->val >= node->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、付费专栏及课程。

余额充值