【遍历链表】个人练习-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;
    }
};
相关推荐
鑫鑫向栄1 小时前
[蓝桥杯]堆的计数
数据结构·c++·算法·蓝桥杯·动态规划
緈福的街口2 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
weixin_419658314 小时前
数据结构之LinkedList
数据结构
小刘不想改BUG5 小时前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
sz66cm7 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先
爱coding的橙子9 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光9 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿9 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
岁忧9 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy9 小时前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·