1 class Solution:
 2     def constructLink(self,lists):
 3         n = len(lists)
 4         if n == 0:
 5             return None
 6         if n == 1:
 7             return ListNode(lists[0])
 8         
 9         head = ListNode(lists[-1])
10         for i in range(n-2,-1,-1):
11             cur = ListNode(lists[i])
12             cur.next = head 
13             head = cur
14         return head
15         
16     def rotateRight(self, head: ListNode, k: int) -> ListNode:
17         lists = []
18         count = 0
19         while head != None:
20             lists.append(head.val)
21             count += 1
22             head = head.next
23         if count == 0:
24             return None
25         k = k % count
26         newlist = lists[count-k:] + lists[:count-k]
27         return self.constructLink(newlist)

先将原来的链表展开,存储到数组中,并计算数组长度。

再将数组按照k值翻转,重新排好顺序。

最后使用尾插法,重建链表。

将复杂问题分开步骤处理,可以使代码更清晰。

posted on 2019-12-10 12:58  Sempron2800+  阅读(126)  评论(0编辑  收藏  举报