zoukankan      html  css  js  c++  java
  • 力扣 — Rotate List()

    题目描述:

    中文:

    给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

    示例 1:

    输入: 1->2->3->4->5->NULL, k = 2
    输出: 4->5->1->2->3->NULL
    解释:
    向右旋转 1 步: 5->1->2->3->4->NULL
    向右旋转 2 步: 4->5->1->2->3->NULL

    示例 2:

    输入: 0->1->2->NULL, k = 4
    输出: 2->0->1->NULL
    解释:
    向右旋转 1 步: 2->0->1->NULL
    向右旋转 2 步: 1->2->0->NULL
    向右旋转 3 步: 0->1->2->NULL
    向右旋转 4 步: 2->0->1->NULL

    英文:

    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(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if k == 0:
                return head
            if head == None:
                return head
            dummy = ListNode(0)
            dummy.next = head
            p = dummy
            count = 0
            while p.next:
                p = p.next
                count += 1
            p.next = dummy.next
            step = count - ( k % count )
            for i in range(0, step):
                p = p.next
            head = p.next
            p.next = None
            return head

    题目来源:力扣

  • 相关阅读:
    BZOJ 2016十连测 D3T3序列
    Luogu3579 Solar Panels
    POI2014解题报告
    BZOJ4377 Kurs szybkiego czytania Luogu 3589[POI2015]KUR
    Luogu3587[POI2015]POD
    BZOJ4386[POI2015]Wycieczki / Luogu3597[POI2015]WYC
    BZOJ4381 : [POI2015]Odwiedziny / Luogu3591[POI2015]ODW
    HDU 1133 Buy the ticket
    HDU RPG的错排 【错排&&组合】
    【转】求逆元的n种方法
  • 原文地址:https://www.cnblogs.com/spp666/p/11644321.html
Copyright © 2011-2022 走看看