Rotate List

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

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步,要考虑k大于链表长度的情况,用count计算链表长度,用k%count更新移动步数。

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @param {ListNode} head
 9     # @param {integer} k
10     # @return {ListNode}
11     def rotateRight(self, head, k):
12         if k==0: return head               #注意‘==’
13         if head==None: return head
14         dummy=ListNode(0)
15         dummy.next=head
16         p=dummy
17         count=0
18         while p.next:                      #计算链表的长度
19             p=p.next
20             count += 1
21         step=count-(k%count)               #向右移动k步,若k大于链表长度,则移动步数是(k%count)
22         p.next=dummy.next
23         for i in range(step):
24             p=p.next                       #通过step找到p的初始位置,使得p.next即为所有需要移动的链表部分
25         head=p.next                        #把需移动的p.next赋给头结点,转移到前面
26         p.next=None                        #并令p.next=None,结尾
27         return head                        #返回此时转移后的head(为什么return dummy.next 会出错)

 

posted @ 2015-06-29 10:14  小榛子  阅读(166)  评论(0编辑  收藏  举报