题目:
旋转链表:给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
思路:
将链表成环进行旋转,对于K,需要判断数目,使用超过了链表的长度。
程序:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return None
        length = 0
        index = head
        while index.next:
            index = index.next
            length += 1
        index.next = head
        length = length + 1
        k = k % length
        for i in range(length - k):
            head = head.next
            index = index.next
        index.next = None
        return head

相关文章:

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