美文网首页LeetCode系列
LeetCode题解-61-向右翻转链表

LeetCode题解-61-向右翻转链表

作者: FreeTheWorld | 来源:发表于2020-03-02 22:21 被阅读0次

问题描述:
将一个单链表,向右翻转k次,注意k可能大于链表长度。
原文链接

# python3

# 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 k==0 or head==None:return head
        current,tail = head,head
        N=1
        while tail.next!=None:
            N+=1
            tail = tail.next
        k = k%N #当k大于链表长度时,等效于翻转K%N次
        tail = head
        i=0
        while i<k:
            tail = tail.next
            i+=1
        while tail.next!=None:
            tail = tail.next
            current = current.next
        tail.next = head
        head = current.next
        current.next=None
        return head

相关文章

网友评论

    本文标题:LeetCode题解-61-向右翻转链表

    本文链接:https://www.haomeiwen.com/subject/zxcwkhtx.html