LeetCode 61 旋转链表

编程入门 行业动态 更新时间:2024-10-25 14:26:45

LeetCode 61 旋转<a href=https://www.elefans.com/category/jswz/34/1769662.html style=链表"/>

LeetCode 61 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:


输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:


输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

解题思路:

闭合为环

力扣

【Leetcode】Python&C++:61. 旋转链表 (链表操作)【每日一题系列20210327】_哔哩哔哩_bilibili

Python代码:

# 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 k == 0 or not head or not head.next:return headcur = headn = 1while cur.next:cur = cur.nextn += 1add = n - k % nif add == n:return headcur.next = headwhile add:cur = cur.nextadd -= 1res = cur.nextcur.next = Nonereturn res

更多推荐

LeetCode 61 旋转链表

本文发布于:2024-02-27 06:07:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1705471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:链表   LeetCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!