【leetcode】61. 旋转链表(python)

【leetcode】61. 旋转链表(python),第1张



细节:

  1. 若 k == 0 (包括取模之后k = 0)时,直接返回原链表即可。
  2. 注意末尾节点指向None。
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head or not head.next or k == 0:
            return head
        p = head
        cnt = 0
        while p:
            p = p.next
            cnt += 1

        k = k % cnt
        if k == 0:
            return head
            
        pre, p = head, head
        for i in range(cnt - k):
            pre = p
            p = p.next
        pre.next = None  # 末尾节点指向None

        res = p
        while p.next:
            p = p.next
        p.next = head
        return res

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/876211.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存