leetcode 61. Rotate List和86. Partition List

目录

[61. Rotate List](#61. Rotate List)

[86. Partition List](#86. Partition List)


61. Rotate List

代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == nullptr)
            return head;
        if(k == 0)
            return head;
        ListNode* cur = head;
        int count = 0;
        while(cur){
            count++;
            cur = cur->next;
        }
        k = k%count;
        if(k == 0)
            return head;

        ListNode *pre = nullptr;
        cur = head;
        for(int i = 0;i < count -k;i++){
            pre = cur;
            cur = cur->next;
        }
        if(pre ==nullptr)
            return head;
        pre->next = nullptr;
        ListNode* newhead = cur;
        while(cur->next){
            cur = cur->next;
        }
        cur->next = head;
        return newhead;
    }
};

86. Partition List

代码:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head == nullptr)
            return nullptr;
        ListNode* left_dummy = new ListNode(-1,nullptr);
        ListNode* right_dummy =new ListNode(-1,nullptr);
        ListNode* leftpre = left_dummy;
        ListNode* rightpre = right_dummy;
        ListNode* cur = head;
        while(cur){
            if(cur->val < x){
                leftpre->next = cur;
                leftpre = cur;
            }else{
                rightpre->next = cur;
                rightpre = cur;
            }
            cur = cur->next;
        }
        leftpre->next = right_dummy->next;
        rightpre->next = nullptr;
        ListNode* ans = left_dummy->next;
        delete left_dummy;
        delete right_dummy;

        return ans;
    }
};
相关推荐
Swift社区7 小时前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
weixin_445054727 小时前
力扣热题51
c++·python·算法·leetcode
smj2302_7968265210 小时前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
sin_hielo13 小时前
leetcode 1975
数据结构·算法·leetcode
2501_9418204913 小时前
面向零信任安全与最小权限模型的互联网系统防护设计思路与多语言工程实践分享
开发语言·leetcode·rabbitmq
2501_9418059314 小时前
一次从接口网关到异步消息驱动架构演化的互联网系统实践技术随笔分享录
leetcode·决策树·贪心算法
黛色正浓15 小时前
leetCode-热题100-二叉树合集(JavaScript)
javascript·算法·leetcode
炽烈小老头16 小时前
【每天学习一点算法 2026/01/05】打乱数组
学习·算法·leetcode
2501_9411497917 小时前
面向微服务异步消息队列与可靠投递的互联网系统高可用设计与多语言工程实践分享
leetcode·决策树
--JR17 小时前
015——图(1.图的相关概念与存储)
数据结构·c++·算法·链表·图论