LeetCode:61. Rotate List - Python

问题描述:

61. 旋转链表

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

示例 :

输入: 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

问题分析:

(1)先用一个指针,遍历一遍链表,求出长度,并在结尾指向头结点,形成环形两边。
(2)再用一个指针,遍历一遍环形链表,找到分割位置,切开返回即可。

Python3实现:

def ListNodetest(n=10):  # 构造测试用例

    if n < 1:return None
    head = ListNode(None)
    point = head
    while n != 0:
        point.next = ListNode(n)
        point = point.next
        n -= 1
    return head.next


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


class Solution:
    def rotateRight(self, head, k):

        if not head: return None

        p = head
        length = 1
        while p.next:  # 获取链表的长度
            p = p.next
            length += 1
        p.next = head  # 此时形成一个环形链表

        k %= length  # k 可能超过链表的长度,取余可以减少不必要的计算
        q = head
        for _ in range(length-k-1):  # 找到要分割的位置
            q = q.next

        ans = q.next  # 切开即可
        q.next = None

        return ans


if __name__ == '__main__':
    solu = Solution()
    head, k = ListNodetest(8), 3
    head = solu.rotateRight(head, k)

    while head:
        print(head.val)
        head = head.next

声明: 总结学习,有问题或不妥之处,可以批评指正哦。

题目链接: leetcode-cn.com/problems/rotate-list/
参考链接: leetcode.com/problems/rotate-list/discuss/186709/short-python-solution-99.7

猜你喜欢

转载自blog.csdn.net/XX_123_1_RJ/article/details/84393871