自学内容网 自学内容网

【LeetCode】旋转链表


一、题目

给你一个链表的头节点 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 * 109


二、解法

先取余,化简一下k,然后找到倒数第k+1个节点,然后做断开重新连接的动作


完整代码

# 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: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head:
            return head
        dummy = cur = ListNode()
        dummy.next = head
        tot = 0
        while cur.next:
            cur = cur.next
            tot += 1
        last = cur
        cur = dummy
        k %= tot
        tmp = cur
        for _ in range(k + 1):
            tmp = tmp.next
        kk = cur
        while tmp:
            kk = kk.next
            tmp = tmp.next
        newHead = kk.next
        if not newHead:
            return dummy.next
        last.next = head
        kk.next = None
        return newHead


原文地址:https://blog.csdn.net/qq_26521261/article/details/140578742

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!