博客主页:🏆李歘歘的博客 🏆
🌺每天不定期分享一些包括但不限于计算机基础、算法、后端开发相关的知识点,以及职场小菜鸡的生活。🌺
💗点关注不迷路,总有一些📖知识点📖是你想要的💗
⛽️今天的内容是 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
头尾相连形成环,寻找断点,斩断
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 head is None or k == 0 :
return head
tmp = head
count = 1
while head.next is not None :
head = head.next
count += 1
head.next = tmp
i = 1
k %= count
while i < count - k :
tmp = tmp.next
i+=1
result = tmp.next
tmp.next = None
return result