LeetCode系列

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

2020-03-02  本文已影响0人  FreeTheWorld

问题描述:
将一个单链表,向右翻转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
上一篇下一篇

猜你喜欢

热点阅读