栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Java&C++题解与拓展——leetcode剑指OfferII 029.排序的循环链表【么的新知识】

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java&C++题解与拓展——leetcode剑指OfferII 029.排序的循环链表【么的新知识】

每日一题做题记录,参考官方和三叶的题解

目录
  • 题目要求
  • 思路:模拟
    • Java
    • C++
  • 总结

题目要求

思路:模拟
  • 在有序的链表中找到合适的插入位置然后插入即可;
  • 先构造一个指向自己的插入值节点 i n s e r t N o d e insertNode insertNode;
  • 当链表为空时返回自己;
  • 当链表中只有一个节点直接插入;
  • 遍历所有节点,找一个合适的位置,也就是当前节点 c u r cur cur的值小于 i n s e r t V a l insertVal insertVal,但是下一节点值大于 i n s e r t V a l insertVal insertVal;
    • 注意在循环链表最大值和最小值的交界处的特殊判断,大于最大值或小于最小值就在这个交界插入。
Java
class Solution {
    public Node insert(Node head, int insertVal) {
        Node insertNode = new Node(insertVal);
        insertNode.next = insertNode;
        if (head == null)
            return insertNode;
        if (head.next == head) {
            head.next = insertNode;
            insertNode.next = head;
            return head;
        }
        Node cur = head;
        while (cur.next != head) {
            if (insertVal >= cur.val && insertVal <= cur.next.val)
                break;
            if (cur.val > cur.next.val) {
                if (insertVal > cur.val || insertVal < cur.next.val)
                    break;
            }
            cur = cur.next;
        }
        insertNode.next = cur.next;
        cur.next = insertNode;        
        return head;
    }
}
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
C++
class Solution {
public:
    Node* insert(Node* head, int insertVal) {
        Node *insertNode = new Node(insertVal);
        insertNode->next = insertNode;
        if (head == nullptr)
            return insertNode;
        if (head->next == head) {
            head->next = insertNode;
            insertNode->next = head;
            return head;
        }
        Node *cur = head;
        while (cur->next != head) {
            if (insertVal >= cur->val && insertVal <= cur->next->val)
                break;
            if (cur->val > cur->next->val) {
                if (insertVal > cur->val || insertVal < cur->next->val)
                    break;
            }
            cur = cur->next;
        }
        insertNode->next = cur->next;
        cur->next = insertNode;        
        return head;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
总结

快乐的链表模拟题,有一次感觉不至于中等……

【今天么的rust可写,赶紧去肝论文了。】


欢迎指正与讨论!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号