标签:
题目来源
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
[LeetCode]题解(python):061-Rotate list
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5093470.html