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 ≤ m ≤ n ≤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