【LeetCode-61】旋转链表

问题

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例

输入: head = [1,2,3,4,5], k = 2
输出: [4,5,1,2,3]

解答

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return nullptr;
        int cnt = 1;
        ListNode *tail = head;
        while (tail->next) {
            cnt++;
            tail = tail->next;
        }
        tail->next = head;
        k = cnt - (k % cnt) - 1; // 头节点需要向右移动的次数
        for (int i = 0; i < k; i++)
            head = head->next;
        ListNode* newHead = head->next;
        head->next = nullptr;
        return newHead;
    }
};

重点思路

  1. 统计链表长度,顺便找到尾节点;
  2. 头尾节点相连;
  3. 断链:移动头节点到需要断链的位置。
posted @ 2021-03-27 11:46  tmpUser  阅读(45)  评论(0编辑  收藏  举报