Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULLExample 2:
Input: 0->1->2->NULL, k = 4 Output:2->0->1->NULL
Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right:0->1->2->NULL
rotate 4 steps to the right:2->0->1->NULL
题意:不断把最后一个node旋转到第一个,反复k次
1 list大法好 (time:O(n), space:O(n)
注意 k如果等于链表len,其实是回到原位的,所以取余就好
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:return None
n = 0
node = head
linklist = []
while(node):
linklist.append(node)
node = node.next
n += 1
k = k%n
while(k > 0):
#linklist[0],linklist[-1] = linklist[-1],linklist[0]
linklist.insert(0,linklist[-1])
del linklist[-1]
k -= 1
for i in range(n-1):
linklist[i].next = linklist[i+1]
linklist[-1].next = None
return linklist[0]
2 回归正道,遍历,time:O(n),sapce:O(1)
找到新list的首尾修改即可
e.g. 1 -> 2 -> 3 ->null ,计算len=3, k=1时 要得到 3 -> 1 ->2 ->null
newhead是3,是从1往后走2个结点得到的,其实就是走 len - k步,所以从head往后遍历 len-k 个结点就是newhead ,同时要记录pre,因为newhead的pre就是新list的结尾,修改pre.next = None
同时原list的结尾指向head即可
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:return None
n = 0
node = head
#计算长度
while(node):
node = node.next
n += 1
k = k%n
if not head.next or k==0:return head
node = head
#找到newhead
for i in range((n - k)):
pre = node
node = node.next
newhead = node
pre.next = None
while(node.next):
node = node.next
node.next = head
return newhead