【Leetcode链表】旋转链表(61)

题目

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

示例 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

示例 2:

输入: 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

解答

思路:先把链表首尾相连,再找到位置断开循环。

通过代码如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# Time: O(n), Space: O(1)
# 令链表首位相连,找位置断开即可。
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next or k == 0:
            return head

        # 令首位相连
        cnt = 0
        c = head
        while c:
            cnt += 1
            p = c
            c = c.next
        p.next = head

        # 旋转数是链表长度的倍数
        if k % cnt == 0:
            p.next = None
            return head

        # 在链表的第for_cnt个节点断开
        for_cnt = cnt - (k % cnt)
        for _ in range(for_cnt):
            p = head
            head = head.next
        p.next = None  # 断开
        return head
posted @ 2019-11-27 11:30  961897  阅读(100)  评论(0编辑  收藏  举报