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;
    }
};
相关推荐
岁忧1 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
Maybyy3 小时前
力扣61.旋转链表
算法·leetcode·链表
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
丶小鱼丶7 小时前
链表算法之【合并两个有序链表】
java·算法·链表
是白可可呀10 小时前
LeetCode 169. 多数元素
leetcode
码农Cloudy.11 小时前
C语言<数据结构-链表>
c语言·数据结构·链表
YuTaoShao11 小时前
【LeetCode 热题 100】148. 排序链表——(解法二)分治
java·算法·leetcode·链表
蒟蒻小袁12 小时前
力扣面试150题--全排列
算法·leetcode·面试
谭林杰13 小时前
散链表基本操作讲解
数据结构·链表