本文共 909 字,大约阅读时间需要 3 分钟。
用双指针找到倒数第n个ListNode的位置,也就是旋转的节点。
这个题只需要注意一下记录链表长度。
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head is None:return None fast = slow = head length = 0 while fast.next: fast = fast.next length += 1 k = k%(length+1) fast = head while k>0 and fast.next: fast = fast.next k -= 1 while fast.next and slow.next: fast = fast.next slow = slow.next if slow.next is None: return head nhead = p = slow.next slow.next = None while p.next: p=p.next p.next=head return nhead
转载地址:http://dbrbb.baihongyu.com/