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;
    }
};
相关推荐
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll3 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐3 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
郝学胜-神的一滴4 天前
深入理解链表:从基础到实践
开发语言·数据结构·c++·算法·链表·架构
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了4 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333334 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
网小鱼的学习笔记4 天前
leetcode876:链表的中间结点
数据结构·链表