[LinkedList]061 Rotate List

  • 分类:LinkedList

  • 考察知识点:LinkedList

  • 最优解时间复杂度:**O(n) **

61. Rotate List

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

代码:

方法:

# 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 or head.next==None:
            return head
        
        index=head
        length=1
        while index.next:
            index=index.next
            length+=1
            
        index.next=head
        
        i=0
        while(i<length-k%length):
            index=index.next
            head=head.next
            i+=1
        index.next=None
        return head

讨论:

1.一个首尾相连的方法,还是挺巧妙的

还是挺巧妙
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • [端午回家,妈妈来接我的时候,路上一个近地告诉我弟弟太瘦了,看着就心疼。我心里就想,还好啊,弟弟那个是正常水平吧。...
    夏未初1997阅读 329评论 2 7
  • 讲了几种拖延的理由: 1,小丑。以拖延为保留搞笑节目。 2,圣人。以照顾别人为目标和价值,对自己的事一拖再拖。(以...
    小可樂阅读 369评论 0 0
  • L_hy阅读 252评论 0 0
  • 1,从本篇文章/音频/视频中我学到的最重要的概念 我们要学会做一个倾听者,不能总是急于指出他人的不足,更多时候,他...
    104尚宁阅读 305评论 2 0