# 61. Rotate List

题目描述:

Given a list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

题目翻译

给定一个链表,将其循环右移k位,k非负。

示例1:

给定 1->2->3->4->5->NULL and k = 2,

返回 4->5->1->2->3->NULL.

解题方案

标签: List

思路:

  • 首先遍历整个链表,计算其长度m,将其首尾相连为一个循环链表。之后找到循环右移k位后的新head,在新head处将链表断开即可。

代码:

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

class Solution:
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head is None:
            return None
        new_tail = head
        tail = head
        length = 1
        while tail.next is not None:
            tail = tail.next
            length += 1
        k = length - (k % length)
        if k == length:
            return head
        i = 1
        while i != k:
            new_tail = new_tail.next
            i += 1
        new_head = new_tail.next
        new_tail.next = None
        tail.next = head
        return new_head

参考资料

  • 作者:张浩天

results matching ""

    No results matching ""