【遍历链表】个人练习-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;
    }
};
相关推荐
Word码1 小时前
[排序算法]希尔排序
c语言·数据结构·算法·排序算法
QT 小鲜肉1 小时前
【数据结构与算法基础】05. 栈详解(C++ 实战)
开发语言·数据结构·c++·笔记·学习·算法·学习方法
靠近彗星2 小时前
3.4特殊矩阵的压缩存储
数据结构·人工智能·算法
网安INF2 小时前
Python核心数据结构与函数编程
数据结构·windows·python·网络安全
.格子衫.3 小时前
018数据结构之队列——算法备赛
数据结构·算法
浩泽学编程4 小时前
【源码深度 第1篇】LinkedList:双向链表的设计与实现
java·数据结构·后端·链表·jdk
怎么没有名字注册了啊5 小时前
求一个矩阵中的鞍点
数据结构·算法
仟千意5 小时前
数据结构:二叉树
数据结构·算法
而后笑面对6 小时前
力扣2025.10.19每日一题
算法·leetcode·职场和发展
·白小白6 小时前
力扣(LeetCode) ——11.盛水最多的容器(C++)
c++·算法·leetcode