61-旋转链表

61、旋转链表

题目:

a1V4KO.png

题解:

此题比较简单,思路也比较明确。本来我的思路是直接遍历到 n - k%n -1 的位置将next复制一份后指向None,然后用复制的继续遍历到屁股指向head。

但看了题解发现,先遍历一般把屁股指向头形成环形 并顺便把链表长度计算一下,然后再到 n - k%n -1 的位置把next当新的头并将next指向None,也可以。

最终选择官方题解的方法,其实没什么区别,先连头后连头罢了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if k == 0 or head == None:
return head
n = 1
old_tail = head
while old_tail.next:
old_tail = old_tail.next
n += 1
old_tail.next = head
new_tail = head
for i in range(n - k % n - 1):
new_tail = new_tail.next
new_head=new_tail.next
new_tail.next = None
return new_head

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器