LeetCode 61. 旋转链表

61. 旋转链表

Difficulty: 中等

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

示例 1:

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

示例 2:

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

提示:

  • 链表中节点的数目在范围 [0, 500]
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10<sup>9</sup>

Solution

将题目分解为三步,第一步拿到链表旋转后的前半段pre,第二步拿到链表旋转的后半段pos,第三步把链表的前半段放在链表后半段的后面。

题目要求是将链表的每个节点向右移动k个位置,k有可能会大于链表的长度l,那么意味着链表前半段的长度distancel - k % l,遍历链表移动distance长度获得前半段pre,剩余的部分为链表的后半段pos,取出后半段之后指向前半段就解决了。

# Definition for singly-linked list.
# 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 not head or not k:
            return head
        t, l = head, 0
        while t:
            l += 1
            t = t.next
        distance = l - k % l
        
        pre = ListNode(-1)
        p = pre
        while distance > 0:
            curNode = ListNode(head.val)
            p.next = curNode
            p = p.next
            head = head.next
            distance -= 1
        p.next = None
        
        res = ListNode(-1)
        pos = res
        while head:
            curNode = ListNode(head.val)
            pos.next = curNode
            pos = pos.next
            head = head.next
        pos.next = pre.next
        return res.next
原文地址:https://www.cnblogs.com/swordspoet/p/14585439.html