• 【力扣 091】61. 旋转链表


    61. 旋转链表

    给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

    示例 1:


    输入:head = [1,2,3,4,5], k = 2
    输出:[4,5,1,2,3]
    示例 2:


    输入:head = [0,1,2], k = 4
    输出:[2,0,1]
     

    提示:

    链表中节点的数目在范围 [0, 500] 内
    -100 <= Node.val <= 100

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/rotate-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    代码实现:

    /**
     * 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) return head;
            ListNode *p = head;
            int num = 0;
            while(p)
            {
                ++num;
                p = p->next;
            }
            if(k % num == 0) return head;
            k = k % num;
    
            ListNode *slow = head, *fast =head;
            while(k--)
                fast = fast->next;
            while(fast->next)
            {
                fast = fast->next;
                slow = slow->next;
            }
            p = slow->next;
            slow->next = nullptr;
            fast->next = head;
            return p;
        }
    };
  • 相关阅读:
    leetcode[9]Palindrome Number
    leetcode[10]Regular Expression Matching
    leetcode[11]Container With Most Water
    leetcode[12]Integer to Roman
    leetcode[13]Roman to Integer
    leetcode[14]Longest Common Prefix
    leetcode[15]3Sum
    leetcode[16]3Sum Closest
    leetcode[17]Letter Combinations of a Phone Number
    leetcode[18]4Sum
  • 原文地址:https://www.cnblogs.com/sunbines/p/16328434.html
Copyright © 2020-2023  润新知