Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
题意:链表向右移动K位
Runtime: 42 ms
思路:
获取链表的长度,s=k%链表长,即为实际移动的位数
s=0,不移动
s>0,将链表右边s位拼接到链表的开头
首先利用快慢指针法,快指正比满指正多走s步后同步走,快指正指向尾结点,慢指针指向要拼接的链表前一结点,然后将慢指针后续链表拼接到开头即可
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def Length(self,head):
l=0
while head:
l=l+1
head=head.next
return l
def rotateRight(self, head, k):
if not head or not head.next:
return head
dummy=ListNode(0)
dummy.next=head
headlen=self.Length(head)
s=k%headlen
if s>0:
slow=fast=dummy
for i in range(s):
fast=fast.next
while fast:
slow=slow.next
fast=fast.next
fast.next=dummy.next
dummy.next=slow.next
slow.next=None
return dummy.next