leetcode_61 旋转链表

861 阅读1分钟

要求

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

image.png

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

image.png

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

  • 链表中节点的数目在范围 [0, 500] 内
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

核心代码

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if head == None or head.next == None:
            return head
        prob = head
        counter = 1
        while prob.next != None:
            counter += 1
            prob = prob.next
        prob.next = head
        prob_new = head
        if k >= counter:
            k = k % counter
        for i in range(counter - k - 1):
            prob_new = prob_new.next
        new_head = prob_new.next
        prob_new.next = None
        return new_head

另一解法

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if head == None:
            return head
        h = ListNode(-1)
        h.next = head
        prob = h
        prob1 = h
        counter = 0
        while prob.next != None:
            counter += 1
            prob = prob.next
        
        if k > counter:
            k = k % counter
        
        for i in range(counter - k):
            prob1 = prob1.next
        
        temp = prob1.next
        prob1.next = None

        prob2 = temp
        hh = ListNode(-1)
        hh.next = temp
        prob2 = hh
        while prob2.next != None:
            prob2 = prob2.next
        prob2.next = h.next
        return hh.next

image.png

解题思路:第一种解法:我们将我们的链表先变成一个圆环,然后我们数出来要在那个节点的位置断开即可;第二种解法:我们直接找到要断开的节点,将后面节点保存起来,然后断开节点后面是None,在遍历到保存节点的最后,然后将我们的头节点接到我们的节点后面,完成旋转操作。