美文网首页Leetcode
Leetcode 61. Rotate List

Leetcode 61. Rotate List

作者: SnailTyan | 来源:发表于2018-10-13 22:24 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Rotate List

    2. Solution

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(!head) {
                return head;
            }
            int n = 0;
            ListNode* pre = nullptr;
            ListNode* current = head;
            while(current) {
                n++;
                pre = current;
                current = current->next; 
            }
            pre->next = head;
            int target = n - k % n;
            current = head;
            while(target) {
                target--;
                pre = current;
                current = current->next;
            }
            pre->next = nullptr;
            return current;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/rotate-list/description/

    相关文章

      网友评论

        本文标题:Leetcode 61. Rotate List

        本文链接:https://www.haomeiwen.com/subject/gkuaaftx.html