zoukankan      html  css  js  c++  java
  • [leetcode]Rotate List @ Python

    原题地址:https://oj.leetcode.com/problems/rotate-list/

    题意:

    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=2,(1,2,3,4,5)循环右移两位变为(4,5,1,2,3)。由于k值有可能比链表长度大很多,所以先要用一个count变量求出链表的长度。而k%count就是循环右移的步数。

    代码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @param k, an integer
        # @return a ListNode
        def rotateRight(self, head, k):
            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
            
  • 相关阅读:
    算法竞赛进阶指南 0.1
    补题 : 过分的谜题
    矩阵快速幂【模板】
    10774: matrix
    火车进出栈问题 【求卡特兰数】
    [最小割]StoerWagner算法
    安装、使用sklearn
    [线段树]跳蚤
    [树形dp][换根]Maximum White Subtree
    [组合数学]Many Many Paths
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3785465.html
Copyright © 2011-2022 走看看