leetcode刷题-61旋转链表

题目

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

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

思路

将原本的链表变成环形链表,然后搜寻到相应位置即可

实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next:
            return head
        tmp = head
        l = 1
        while head.next != None:
            head = head.next
            l += 1
        head.next = tmp
        for i in range(l - k % l - 1):
            tmp = tmp.next
        print(tmp.val)
        tmp2 = tmp.next
        tmp.next = None
        return tmp2

 

posted @ 2020-08-06 09:48  maoguai  阅读(84)  评论(0编辑  收藏  举报