leetcode61. Rotate List

Posted JESSET

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode61. Rotate List相关的知识,希望对你有一定的参考价值。

题目说明

https://leetcode-cn.com/problems/rotate-list/description/
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

解法1

/*
 * 时间复杂度:O(n)
 * 得到链表长度,k对其取余(对链表进行旋转次数是长度的整数倍数时,链表是不变的),求得的k值即有效的旋转次数
 * 每次旋转,将最后一个结点移到第一个结点位置
 * 所以每次都需要定位到最后一个结点前一个结点的位置,方便进行移动操作
 */
ListNode* rotateRight(ListNode* head, int k) {
    ListNode *dummy = new ListNode(0);
    dummy->next = head;

    ListNode *pre = dummy->next;
    ListNode *cur = NULL;

    if (pre == NULL || pre->next == NULL)
        return head;

    int len = 1;
    while(pre->next){
        pre=pre->next;
        len ++;
    }

    k = k % len;

    for (int i = 0; i < k; i ++){
        pre = dummy->next;
        while(pre->next->next)
            pre = pre->next;
        cur = pre->next;
        pre->next = cur->next;
        cur->next = dummy->next;
        dummy->next = cur;
    }
    return dummy->next;
}

解法2

/*
 * 时间复杂度:O(n)
 * 使用双指针,获取到需要旋转的区间,然后整体旋转到头部
 */
ListNode* rotateRight(ListNode* head, int k) {
    ListNode *dummy = new ListNode(0);
    dummy->next = head;

    ListNode *pre = dummy->next;
    ListNode *cur = NULL;
    ListNode *next = NULL;

    if (pre == NULL || pre->next == NULL)
        return head;

    int len = 1;
    while(pre->next){
        pre=pre->next;
        len ++;
    }

    k = k % len;
    if (k == 0)
    return head;
    ListNode *start = dummy->next;
    ListNode *end =  dummy->next;

    for (int i = 0; i < k; i ++){
        end = end->next;
    }

    while(end->next){
        start = start->next;
        end = end->next;
    }

    next = dummy->next;
    dummy->next = start->next;
    end->next = next;
    start->next = NULL;

    return dummy->next;
}

以上是关于leetcode61. Rotate List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 61. Rotate List 考虑边界条件

一天一道LeetCode#61. Rotate List

LeetCode 61. Rotate List

Leetcode61 Rotate List

Leetcode 61 -- Rotate List

leetcode61. Rotate List