题目

给定一个链表,旋转链表,将链表每个节点向右移动 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

相关文章:

  • 2021-07-12
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
  • 2021-08-24
  • 2022-02-10
  • 2021-04-05
猜你喜欢
  • 2021-07-10
  • 2021-05-12
  • 2021-11-19
  • 2022-01-05
  • 2021-10-10
  • 2021-08-29
  • 2021-07-16
相关资源
相似解决方案