Description
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
给定一个链表,将链表向右旋转 k 个位置,其中 k 是非负数。
示例:
给定 1->2->3->4->5->NULL 且 k = 2,
返回 4->5->1->2->3->NULL.
Solution
采用fast-slow双指针,令fast指针先移动k步,步长为1,从而与slow指针形成k步长的窗口。然后两个指针同时移动,当fast指针到达最末尾的时候,窗口的大小就是要将其旋转到开头的大小。将fast指向head,slow指向None,则完成旋转。
注意:题目中的k有可能大于链表的总长度,因此需要对k取模。先遍历链表得到长度count,k%count就是实际旋转的长度。
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 22:01:43 2018
@author: Saul
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None:
return head
count = 0
p = head
while p:
count += 1
p = p.next
k = k%count
if k == 0:
return head
fast = slow = head
while k>0:
k -= 1
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
newhead = slow.next
fast.next = head
slow.next = None
return newhead