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

 

转载于:https://www.cnblogs.com/pkuYang/p/4434263.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值