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;
    }
};
相关推荐
tju新生代魔迷1 小时前
数据结构:双向链表
数据结构·链表
学c语言的枫子3 小时前
数据结构——双向链表
c语言·数据结构·链表
共享家95276 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi8 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
楼田莉子8 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
tju新生代魔迷8 小时前
数据结构:单链表以及链表题
数据结构·链表
dragoooon348 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
hsjkdhs8 小时前
数据结构之链表(单向链表与双向链表)
数据结构·链表·指针
轮到我狗叫了9 小时前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode
dragoooon3410 小时前
[优选算法专题二滑动窗口——串联所有单词的子串]
数据结构·c++·学习·算法·leetcode·学习方法