LeetCode 61. Rotate List

73 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第7天,点击查看活动详情

LeetCode 61. Rotate List

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

示例 1:

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

示例 2:

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

样例

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL\

解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL\

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL\

解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

提示:

  • 链表中节点的数目在范围 [0, 500] 内
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

算法分析

k可能会很大,需要对k进行处理 k = k % n,n是链表的长度

创建first和second指针,同时指向虚拟头结点,先让first先走k步,再让first和second同时往后走,直到first走到最后一个元素位置,如图所示

1、让first指向开头(dummy.next)
2、让开头(dummy.next)指向second.next
3、让second指向null

时间复杂度 O(n)

ac 代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null||k == 0) return head;
        int n = 0;
        ListNode p = head;
        while(p != null)
        {
            n ++;
            p = p.next;
        }
        k %= n;
        if(k == 0) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        while(k -- > 0) first = first.next;

        while(first.next != null)
        {
            first = first.next;
            second = second.next;
        }
        first.next = dummy.next;
        dummy.next = second.next;
        second.next = null;

        return dummy.next;
    }
}

C++代码

C++ 代码
/**
 * 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;
        int n = 0;
        ListNode *p = head;
        while (p){
            n ++ ;
            p = p->next;
        }
        k %= n;
        if (!k) return head;
        ListNode *first = head;
        while (k -- && first) first = first->next;
        ListNode *second = head;
        while (first->next){
            first = first->next;
            second = second->next;
        }
        first->next = head;
        head = second->next;
        second->next = 0;
        return head;
    }
};