[Leetcode]@python 61. Rotate List

题目链接:https://leetcode.com/problems/rotate-list/


 题目大意:链表向右旋转K位


 解题思路:链表操作,注意的是k有可能比链表长度要长,要将k mod 链表的长度


 代码(python):

 1 # Definition for singly-linked list.
 2 class ListNode(object):
 3     def __init__(self, x):
 4         self.val = x
 5         self.next = None
 6 
 7 class Solution(object):
 8     def rotateRight(self, head, k):
 9         """
10         :type head: ListNode
11         :type k: int
12         :rtype: ListNode
13         """
14 
15         if k == 0 or head==None:
16             return head
17 
18         node = ListNode(0)
19         node.next = head
20 
21         t = node
22         size = 0
23         while t.next:
24             t = t.next
25             size += 1
26 
27         t.next = node.next
28 
29         for i in range(size-(k%size)):
30             t = t.next
31         head = t.next
32         t.next = None
33         return head
View Code

原文地址:https://www.cnblogs.com/slurm/p/5110023.html