Leetcode 61. Rotate List

本文深入探讨了链表数据结构中的一种特殊操作——链表旋转。通过计算链表长度并利用模运算,文章详细解释了如何有效地实现链表的右旋转k个位置,包括特殊情况的处理,如链表为空或k为0的情况。此外,还提供了完整的Python代码实现,帮助读者理解算法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Calculate the length of the list and use k%length.

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

class Solution:
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k==0:
            return head
        l=head
        count=0
        while(not l==None):
            l=l.next
            count=count+1
        r=k%count
        if r==0:
            return head
        p=head
        for i in range(count-r-1):
            p=p.next
        q=p.next
        p.next=None
        tmp=q
        for i in range(r-1):
            tmp=tmp.next
        tmp.next=head
        return q
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值