leetcode------Rotate List

标题: Rotate List
通过率: 21.8%
难度: 中等

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=K%len(num)

num=[1,2,3,4,5],k=2

第一步,翻转

num=[5,4,3,2,1]

第二步找到k点,将k点之前的翻转一次。k点之后的翻转一次

num=[45,123]

本题是链表用翻转的就会变得麻烦,但是可以看出来翻转的链表仍然有局部有序

具体步骤如下:

第一个指针fisrt往下遍历k次。

第二个指针second从头开始,和first指针同时走,一直等到first走到最后一个节点。如下图

1  -   2  -    3   -  4  -       5

                 ⬆️                 ⬆️

               second          first

 

tmp指针只向second的下一个节点。

然后将fisrt指向链表的头部,second指空,那么翻转后的链表的头部就是tmp

具体代码如下:

 1 # Definition for singly-linked list.

 2 # class ListNode:

 3 #     def __init__(self, x):

 4 #         self.val = x

 5 #         self.next = None

 6 

 7 class Solution:

 8     # @param head, a ListNode

 9     # @param k, an integer

10     # @return a ListNode

11     def rotateRight(self, head, k):

12         if k==0 or head==None or head.next==None or k==0:return head

13         count,og_start=0,head

14         while head!=None:

15             head=head.next

16             count+=1

17         first,second,k=og_start,og_start,k%count

18         if k==0:return og_start

19         for i in range(k):first=first.next

20         while first.next!=None:

21             first=first.next

22             second=second.next

23         tmp=second.next

24         second.next=None

25         first.next=og_start

26         return tmp

 

你可能感兴趣的:(LeetCode)