【遍历链表】个人练习-Leetcode-LCR 029. 循环有序列表的插入

题目链接:https://leetcode.cn/problems/4ueAj6/description/

题目大意:给出一个循环链表中间的某个结点的指针head(这个并非真正的头),这个链表从头到尾是非递减的,唯一可能出现递减的地方是【尾部连回头部】处。现在给一个值insertVal,要求将该值插入链表中,保持非递减性质不变。返回的还是原来的head指针。

思路:(1)先考虑正常的从头到尾非递减的情况,如果插入值val与某个结点值nowv相同,那么直接插到其后面就行。否则无论是大了还是小了,都得再往后递归。

(2)如果刚好碰到尾部接头部处,那么如果val比尾部值大或者比头部值小,都可以直接插在尾部值后。否则往后递归。

(3)有一种特殊情况是全链表的元素相同。此时我们无法找到(1)(2)中所谓的【尾部接到头部】处(因为不存在nowv > nxtv的情况了),因此单独做判断。这这种情况,val插到任意处都行。

完整代码

cpp 复制代码
class Solution {
public:
    void inop(Node* nd, int val, Node* res) {
        int nowv = nd->val;
        if (val == nowv) {
            Node* tmp = nd->next;
            nd->next = res;
            res->next = tmp;
            return;
        }
        int nxtv = nd->next->val;
        if (nowv == nxtv) 
            inop(nd->next, val, res);
        else if (nowv < nxtv) {
            if (val < nowv)
                inop(nd->next, val, res);
            else { // val > nowv
                if (val <= nxtv) {
                    res->next = nd->next;
                    nd->next = res;
                    return;
                }
                else
                    inop(nd->next, val, res);
            }
        }
        else { // nowv > nxtv, final node
            if (val >= nowv) {
                res->next = nd->next;
                nd->next = res;
                return;
            }
            else { // val < nowv
                if (val <= nxtv) {
                    res->next = nd->next;
                    nd->next = res;
                    return;
                }
                else // val > nxtv
                    inop(nd->next, val, res);
            }
        }
    }

    Node* insert(Node* head, int insertVal) {
        Node* res = new Node(insertVal); 
        if (head == nullptr) {
            res->next = res;
            return res;
        }

        Node* temp = head->next;
        int headv = head->val;
        bool flag = true;
        while (temp != head) {
            if (temp->val != headv) {
                flag = false;
                break;
            }
            temp = temp->next;
        }    
        if (flag) {
            res->next = head->next;
            head->next = res;
            return head;
        }

        inop(head, insertVal, res);
        return head;
    }
};
相关推荐
hn小菜鸡8 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题10 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
_周游10 天前
【数据结构】_二叉树OJ第二弹(返回数组的遍历专题)
数据结构·算法
双叶83610 天前
(C语言)Map数组的实现(数据结构)(链表)(指针)
c语言·数据结构·c++·算法·链表·哈希算法
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
转码的小石10 天前
Java面试复习指南:并发编程、JVM、Spring框架、数据结构与算法、Java 8新特性
java·jvm·数据结构·spring·面试·并发编程·java 8
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
LZA18510 天前
数据结构day1
数据结构
稳兽龙10 天前
P3258 [JLOI2014] 松鼠的新家
数据结构·c++·算法·深度优先·lca