Reverse Linked List II

Source: Internet
Author: User

https://leetcode.com/problems/reverse-linked-list-ii/

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->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.

Title: Reverse the nodes of the specified position segment. (referring to the inverse method of the reverse function of reverse Nodes in K-group)

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param {ListNode} head9     #@param {integer} mTen     #@param {integer} n One     #@return {ListNode} A     defReversebetween (self, head, M, N): -         ifHead==noneorhead.next==None: -             returnHead thedummy=listnode (0) -dummy.next=Head -head1=Dummy -          forIinchRange (m-1): +Head1=head1.next#Head1 placed in the previous item of the starting M -P=head1.next#p placed at start item m +          forIinchRange (N-M):#Loop n-m The following operations, all subsequent items of item 1th are sequentially pre-placed, leading to reverse order ATmp=p.next; P.next=tmp.next#Remove the 2nd item and keep the back connection atTmp.next=head1.next; Head1.next=tmp#Place the 2nd item at the beginning of the row sequence -         returnDummy.next#2,3,4,5--3,2,4,5--4,3,2,5--5,4,3,2, the number of the back of 2 is pre-placed, and it takes n-m times to do this

Reverse Linked List II

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.