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;
    }
};
相关推荐
Vect__17 分钟前
记录3.20和3.21做过的一些力扣的思考
linux·算法·leetcode
计算机安禾30 分钟前
【C语言程序设计】第38篇:链表数据结构(二):链表的插入与删除操作
c语言·开发语言·数据结构·c++·算法·链表
灰色小旋风1 小时前
力扣17 电话号码的字母组合(C++)
c++·算法·leetcode
历程里程碑1 小时前
链表--排序链表
大数据·数据结构·算法·elasticsearch·链表·搜索引擎·排序算法
美式请加冰1 小时前
栈的介绍和使用(算法)
数据结构·算法·leetcode
重生之我是Java开发战士1 小时前
【递归、搜索与回溯】FloodFill算法:图像渲染,岛屿数量,岛屿的最大面积,被围绕的区域,太平洋大西洋水流问题,扫雷游戏,衣橱整理
算法·leetcode·深度优先
j_xxx404_1 小时前
力扣--分治(快速排序)算法题I:颜色分类,排序数组
数据结构·c++·算法·leetcode·排序算法
阿Y加油吧2 小时前
力扣打卡day08——轮转数组、除自身外乘积
数据结构·算法·leetcode
im_AMBER2 小时前
Leetcode 143 搜索插入位置 | 搜索二维矩阵
数据结构·算法·leetcode
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2025.03.21 题目:3643.垂直翻转子矩阵
笔记·leetcode·矩阵