zoukankan      html  css  js  c++  java
  • Leetcode 61. Rotate List

    Decription: Given the head of a linked list, rotate the list to the right by k places.

    Link: https://leetcode.com/problems/rotate-list/

    思路: 假设链表的长度是 length, 通过例子,我们发现 k < length, rotate k times, k >= length, k = k % length times should be rotated. 所以 1) k = k % length. 然后我们发现向右移动k个,实际上是找到倒数第k个位置,把后面的全部元素放到开头来,所以只需找到两个关键Node, 倒数 k-1 (temp)和结尾end,然后第k个元素是new head (nhead),end.next = head, temp.next = None.

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if not head: return head
            if not head.next: return head
            if k == 0: return head
            
            length = 0
            nodes = []
            p = head 
            while p:
                nodes.append(p)
                p = p.next
                length += 1
            # print(length)
            k = k % length
            if k == 0:
                return head
            else:
                temp = nodes[length - k -1]
                nhead = temp.next
                temp.next = None
                end = nodes[length - 1]
                end.next = head
                return nhead

    日期: 2020-11-16 今天regular meeting 被提早了,惊慌失措,又是暖和的冬日

  • 相关阅读:
    hdu 1856 More is better
    hdu 1014 Uniform Generator
    hdu 1412 {A} + {B}
    hdu 1022 Train Problem I
    hdu 1027 Ignatius and the Princess II
    hdu 2377 Bus Pass
    POJ 1141 Brackets Sequence
    guava学习,集合专题
    org.apache.commons等常用工具学习
    utf-8mb4和排序规则
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/13986639.html
Copyright © 2011-2022 走看看