【leetcode】Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

思路:

  • 将链表尾部和头部连起来,顺便算出链表长度len
  • 计算k% len,把尾指针移动到位,然后断开


/**
 * 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 == NULL)
            return head;
        ListNode* tail = head;
        ListNode* newhead = head;
        int len = 1;
        while (tail->next != NULL)
        {
            tail = tail->next;
            ++len;
        }
        tail->next = head;
        k %= len;
        for (int i = 0; i < len - k; ++i)
        {
            tail = tail->next;
        }
        newhead = tail->next;
        tail->next = NULL;
        return newhead;
    }
};


你可能感兴趣的:(练习,算法,C++)