61. Rotate List

2019-05-30  本文已影响0人  jecyhw

题目链接

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

解题思路

直接看代码。

代码

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL) {
            return head;
        }

        //先算节点数量
        int count = 0;
        ListNode *cur = head;
        while (cur != NULL) {
            count++;
            cur = cur->next;
        }

        //算出从第几个节点开始旋转
        k = count - k % count;
        if (k == count) {
            return head;
        }
        cur = head;
        for (int i = 0; i < k - 1; ++i) {
            cur = cur->next;
        }
        ListNode* newHead = cur->next;
        cur->next = NULL;

        cur = newHead;

        while (cur->next != NULL) {
            cur = cur->next;
        }
        cur->next = head;

        return newHead;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读