每日一题力扣61 迷

 

给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next: return head
        # 链表个数
        num = 0
        p = head
        while p:
            num += 1
            p = p.next
        k = num - k % num
        p = head
        # 找前一段链表
        while k > 1:
            p = p.next
            k -= 1
        head1 = p.next
        if not head1: return head
        #前一段链表最后至空
        p.next = None
        p = head1
        # 后一段链表和前一段链表连接起来
        while p.next:
            p = p.next
        p.next = head
        return head1

 

posted @ 2021-03-14 13:28  小千北同学超爱写代码  阅读(57)  评论(0编辑  收藏  举报