61. Rotate List/旋转链表

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

AC代码

int calcLen(ListNode* head) {
    int len = 0;
    while (head) {
        len++;
        head = head->next;
    }
    return len;
}

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return NULL;
        int len = calcLen(head), r = k % len;
        ListNode *pre = head, *post = head;
        for (int i = 0; i < r; ++i) post = post->next;
        while (post->next) {
            pre = pre->next;
            post = post->next;
        }
        ListNode* thead = pre->next;
        if (!thead) return head;
        post->next = head;
        pre->next = NULL;
        return thead;
    }
};

总结

求链表长度和实际旋转长度=>找到旋转后的头=>拼接原链表首尾=>切断新头节点和上一个节点的关联

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,294评论 3 20
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 中午孩子回来说同学们都喜欢揪他鸭绒衣的毛领子。这件衣服上小学时都有人揪,扣子都被揪坏了现在还是有人喜欢揪。孩子还告...
    燕子136阅读 110评论 0 0
  • 如果不是山贼灭门,我还在高高的墙院内做着大小姐;如果不是面部狰狞的疤痕,我还能靠色相混口饭吃。只是现在我什么都没有...
    陌上花开mshk阅读 488评论 0 4
  • 夏天是一个神奇的季节 它有着炎热的气温 也有着凉爽的微风 它会在温度爆表的时候 送来一阵小风降温 像是置身于沙漠之...
    _南茗_阅读 252评论 0 0