[Leetcode] Reverse Linked List II @ Python

Source: Internet
Author: User
Tags diff prev

Original title address: https://oj.leetcode.com/problems/reverse-linked-list-ii/

Test instructions

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->NULL , m = 2 and n = 4,

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

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

Problem-solving ideas: Flipping the list of topics. Please use the brick Thinking (Building block):

Here are the necessary building blocks: List flipping operations:

Current.next, prev, current = prev, current, Current.next

Code:

#Definition for singly-linked list.#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#@param head, a listnode    #@param m, an integer    #@param n, an integer    #@return a ListNode    defReversebetween (self, head, M, N): diff, Dummy= N-m, ListNode (0) Dummy.next=Head prev, current=Dummy, Dummy.next whileCurrent andM >1: prev, current=Current , Current.next m-= 1last_swapped, first_swapped=Prev, current whileCurrent andDiff >=0:current.next, prev, current=prev, Current, Current.next diff-= 1Last_swapped.next, First_swapped.next=Prev, currentreturnDummy.next#Reverse partial Linked List        #Refer figure1:http://images.cnitblog.com/i/546654/201404/072244468407048.jpg        #refer:http://www.cnblogs.com/4everlove/p/3651002.html        #Refer:http://stackoverflow.com/questions/21529359/reversing-a-linked-list-in-python        #1 --2--3--4--5        #               #First_swapped.next = current        #       __________________          #       ^                 |         #       | V        #1 2 <--3 <--4 5        # | ^        #V ________________|        #Last_unswapped.next=prev

[Leetcode] Reverse Linked List II @ Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.