【LeetCode】92. Reverse Linked List II 解题报告(Python)

【LeetCode】92. Reverse Linked List II 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/reverse-linked-list-ii/description/

题目描述:

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

题目大意

把单链表中第m–n个元素进行翻转。

解题方法

其实就是翻转链表的而变形题目了。做法大家都能想出来,进行一遍遍历,把第m到n个元素进行翻转,即依次插入到第m个节点的头部。这个题还是有意思的。建议后面再多做几遍。

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

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        count = 1
        root = ListNode(0)
        root.next = head
        pre = root
        while pre.next and count < m:
            pre = pre.next
            count += 1
        if count < m:
            return head
        mNode = pre.next
        curr = mNode.next
        while curr and count < n:
            next = curr.next
            curr.next = pre.next
            pre.next = curr
            mNode.next = next
            curr = next
            count += 1
        return root.next

日期

2018 年 6 月 24 日 ———— 今天请客吃了海底捞~

猜你喜欢

转载自blog.csdn.net/fuxuemingzhu/article/details/80794665