凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 61. Rotate List

分类:algorithm| 发布时间:2017-03-12 23:17:00


题目

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.

题意

给出一个列表,往右旋转 k 个位置。

解法

/**
 * 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;
        ListNode *i = head;
        int len = 1;
        while (i->next != NULL) {
            ++len;
            i = i->next;
        }

        i->next = head;
        int newTailDist = len - (k % len) - 1;
        i = head;
        while (newTailDist--) {
            i = i->next;
        }

        ListNode *newHead = i->next;
        i->next = NULL;
        return newHead;
    }
};