栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Leetcode题目:python实现 旋转链表(遍历+循环)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode题目:python实现 旋转链表(遍历+循环)

题目: 旋转链表

思路:
1.首先获取链表的长度,判断旋转次数k和长度的关系,得到实际旋转次数 k = m o d ( k , l e n g t h ) k = mod(k,length) k=mod(k,length)。
2.对链表执行k次往右移动一次的操作。

class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if head == None or head.next ==None:
            return head
        length = self.get_length(head)
        # 移动length次,等于不变
        k = k % length
        for i in range(k):
            head = self.rotate1Right(head)
        return head
    # 链表往右移动一次
    def rotate1Right(self, head):
        result = ListNode()
        cur = result 
        # 循环到倒数第二个结点
        while head.next != None:
            cur.next = ListNode()
            cur = cur.next
            cur.val = head.val
            head = head.next
        # 最后一个节点的值赋给头结点
        result.val = head.val
        return result
    # 获取链表的长度
    def get_length(self,head):
        count = 0
        while head != None:
            count = count+1
            head =head.next
        return count
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/840122.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号