LeetCode 刷题【61. 旋转链表】

61. 旋转链表

自己做

解:截取拼接

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) {
        ListNode *p = head, *q = head, *r = head;
        int l = 0;                          //链表长

        if(head == nullptr || head->next == nullptr)                 //没有移动空间
            return head;

        while(p != nullptr){                //计算链表长
            p = p -> next;
            l++;
        }
        p = head;                           //归位p

        //调整k
        k %= l;

        if(k == 0)                          //为0则不移动
            return head;

        for(int i = 0; i < k; i++)          //q、r包含k个元素
            r = r->next;

        if(k > 0)
            q = p->next;

        while(r->next != nullptr){        //使r指向尾部
            p = q;
            r = r->next;
            q = q->next;
        }

        p->next = nullptr;
        r->next = head;

        return q;

    }
};
相关推荐
岁忧3 小时前
(LeetCode 面试经典 150 题) 200. 岛屿数量(深度优先搜索dfs || 广度优先搜索bfs)
java·c++·leetcode·面试·go·深度优先
一枝小雨3 小时前
【OJ】C++ vector类OJ题
数据结构·c++·算法·leetcode·oj题
Tisfy3 小时前
LeetCode 3516.找到最近的人:计算绝对值大小
数学·算法·leetcode·题解
自信的小螺丝钉3 小时前
Leetcode 206. 反转链表 迭代/递归
算法·leetcode·链表
黑色的山岗在沉睡4 小时前
LeetCode 189. 轮转数组
java·算法·leetcode
墨染点香4 小时前
LeetCode 刷题【65. 有效数字】
算法·leetcode·职场和发展
Tisfy4 小时前
LeetCode 3027.人员站位的方案数 II:简单一个排序O(n^2)——ASCII图解
leetcode·题解·思维·排序·hard
源代码•宸4 小时前
Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
c++·经验分享·算法·leetcode·位运算