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

# 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: return head
        # 常规写法
        l = []
        while head:
            l.append(head.val)
            head = head.next
        
        length = len(l)
        _k = k % length
        _l = l[length - _k:] + l[: length - _k]
        
        dummy = ListNode(0)
        cur = dummy

        for num in _l:
            cur.next = ListNode(num)
            cur = cur.next
        
        return dummy.next

 

posted @ 2021-11-03 21:36  风不再来  阅读(31)  评论(0编辑  收藏  举报