(Leetcode 92) Reverse Linked List II

Source: Internet
Author: User

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 Requirements:

This is a variant of the inverted list, and a simple inverted list implementation can refer to the http://www.cnblogs.com/AndyJee/p/4461502.html

Reverses the partial list (flips the elements between the first m nodes to the nth node)

Note the point:

In-place in situ, that is, not to open up additional node space

One-pass One traversal

Problem Solving Ideas:

1. Find the first node of M, find the nth node, and save the M-1 node and the n+1 node by the pointer;

2. Reverse the elements between the first and the nth nodes;

3, the 1~m, M~n, n~length three parts connected together, here need to consider whether M equals 1, that is, whether it is the head node. If yes, point the head to the nth node;

4. Return the head node pointer.

Reference code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Reversebetween (listnode* head,intMintN) {if(Head==null | | head->next==NULL)returnHead; ListNode*prev=Head; ListNode*curr=Head; ListNode*next=Head; ListNode*mprev=NULL; ListNode*mth=NULL; ListNode*nth=NULL; ListNode*nnext=NULL;  for(intI=1; curr!=null;i++) {Next=curr->Next; if(i==m) {Mprev=prev; MTh=Curr; }            if(I>m && i<=N) Curr->next=prev; if(i==N) {NTh=Curr; NNext=Next; } prev=Curr; Curr=Next; }                if(m==1) {mTh->next=NNext; Head=nTh; }        Else{Mprev->next=nTh; MTh->next=NNext; }                returnHead; }};

(Leetcode 92) 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.