zoukankan      html  css  js  c++  java
  • [leetcode]Reverse Linked List II @ Python

    原题地址:https://oj.leetcode.com/problems/reverse-linked-list-ii/

    题意:

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

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

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

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    解题思路:翻转链表的题目。

    代码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @param m, an integer
        # @param n, an integer
        # @return a ListNode
        def reverseBetween(self, head, m, n):
            if head == None or head.next == None:
                return head
            dummy = ListNode(0); dummy.next = head
            head1 = dummy
            for i in range(m - 1):
                head1 = head1.next
            p = head1.next
            for i in range(n - m):
                tmp = head1.next
                head1.next = p.next
                p.next = p.next.next
                head1.next.next = tmp
            return dummy.next
  • 相关阅读:
    列表、元组、字典练习
    周总结04
    站立会议07
    人月神话阅读笔记01
    站立会议06
    站立会议05
    站立会议04
    典型用户需求分析第一期
    站立会议03
    站立会议02
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3783342.html
Copyright © 2011-2022 走看看