题目链接:61.旋转链表
写法一:暴力
class Solution(object):def rotateRight(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""# 暴力:每次移动一个,时间复杂度 O(N^2),空间复杂度O(1)if not head or not head.next:return headp, cnt = head, 0while p:p = p.nextcnt += 1 # cnt: 链表长度if k > cnt:k = k % cnth, p = head, headwhile k:while p.next:pre = pp = p.nextpre.next = Nonep.next = hh = pk -= 1return h
写法二
# 循环右移, 时间复杂度O(n), 空间复杂度O(1)
# 思路:指针遍历到倒数第k个元素,将其后所有元素插入到链表头部。# 如何确定倒数第k个位置的元素?# -->遍历两遍链表,第一遍遍历确定链表元素总个数cnt。第二遍遍历到第cnt-k个位置就是倒数第k个元素。# 注意:如果 k > len(head): 取余数,相当于移动余数个元素
class Solution(object):def rotateRight(self, head, k):""":type head: ListNode:type k: int:rtype: ListNode"""if not head or not head.next: # 0或者1个元素,移动多少个位置都还是原样return headp, cnt = head, 0while p: # 确定链表元素总个数p = p.nextcnt += 1k = k % cnt # 取余数,循环右移余数个位置if k == 0: return headp1 = headfor i in range(cnt - k): # 寻找倒数第k个位置pre1 = p1p1 = p1.nextpre1.next = None # 在倒数第k个位置,断开链表hh = p1 # hh 为新链表的头指针while p1.next: # 寻找到最后一个元素p1 = p1.nextp1.next = head # 让最后一个元素的指针指向headreturn hh