首页 > 试题广场 >

旋转链表

[编程题]旋转链表
  • 热度指数:5316 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定链表的头节点,旋转链表,将链表每个节点往右移动 k 个位置,原链表后 k 个位置的节点则依次移动到链表头。

即,例如链表 : 1->2->3->4->5 k=2 则返回链表 4->5->1->2->3

数据范围:链表中节点数满足
示例1

输入

{1,2,3,4,5},2

输出

{4,5,1,2,3}
示例2

输入

{1,2,3},3

输出

{1,2,3}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def rotateLinkedList(self , head: ListNode, k: int) -> ListNode:
        # write code here
        l_len = 0
        point = head
        while point is not None:
            l_len += 1
            point = point.next
        if l_len == 0:
            return head

        k = k%l_len
        if k == 0:
            return head

        point = head
        next_point = point
        for i in range(k):
            next_point = next_point.next

        while next_point.next is not None:
            next_point = next_point.next
            point = point.next

        new_head = point.next
        point.next = None
        next_point.next = head
        return new_head


发表于 2024-05-29 23:16:40 回复(0)