Q:

给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL


链接:https://leetcode-cn.com/problems/rotate-list/description/

思路:

代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head:
            return []
        stack=[]
        pre = head
        while pre.next:
            stack.append(pre)
            pre = pre.next
        stack.append(pre)
        move_ = k % len(stack)
        if move_ == 0:
            return head
        new_head = stack[-move_]
        stack[-move_-1].next = None
        stack[-1].next = stack[0]
        return new_head

【Leetcode_总结】61. 旋转链表 - python

相关文章: