• [LeetCode]题解(python):061-Rotate list



    题目来源


    https://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.


    题意分析


    Input:a list of node 

    Output:a list of node shift to right

    Conditions:链表右移


    题目思路


    总体思路是链表右移,关键是右移k可能大于实际长度,所以先遍历一次求长度,然后再求模得到真正右移数量

    PS:对于链表操作,每次在前面添加一个节点这个方法很好用,特别注重边界条件

    PS2:尽量用xrange代替range


    AC代码(Python)


     1 __author__ = 'YE'
     2 
     3 # Definition for singly-linked list.
     4 class ListNode(object):
     5     def __init__(self, x):
     6         self.val = x
     7         self.next = None
     8 
     9 class Solution(object):
    10     def rotateRight(self, head, k):
    11         """
    12         :type head: ListNode
    13         :type k: int
    14         :rtype: ListNode
    15         """
    16         if k == 0 or head == None:
    17             return head
    18 
    19         addFirst = ListNode(0)
    20         addFirst.next = head
    21         # move variable
    22         p = addFirst
    23         #the length of list
    24         count = 0
    25         while p.next != None:
    26             p = p.next
    27             count += 1
    28         p.next = addFirst.next
    29         #the real step to shift right
    30         step = count - (k % count)
    31         p = addFirst.next
    32         for i in xrange(1, step):
    33             p = p.next
    34         head = p.next
    35         p.next = None
    36 
    37         return head
  • 相关阅读:
    Markdown
    DNS解析流程
    maven 的各种命令
    ES6初体验——(1)let和const命令
    table相关的选择器 & children()与find()的区别 & 选择器eq(n)与nth-child(n)的差异
    Java MD5加密类
    POI操作Excel异常Cannot get a text value from a numeric cell
    MyEclipse+SSH开发环境配置
    JdbcTemplate详解
    Spring配置声明
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5093470.html
Copyright © 2020-2023  润新知