Reverse a linked list from positionMToN. Do it in-place and in one-pass.
For example:
Given1->2->3->4->5->NULL
,M= 2 andN= 4,
Return1->4->3->2->5->NULL
.
Note:
GivenM,NSatisfy the following condition:
1 ≤M≤N≤Length of list.
Train of Thought 1: To facilitate M = 1 processing, create the head node tmphead for the linked list, which corresponds to the above example, Lt-> val = 1; lt_next-> val = 2; RT-> val = 4; rt_next-> val = 5;
Then, flip the Linked List (lt_next-> next = rt_next) between (lt_next, RT );
Code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode tmphead(-1); tmphead.next=head; ListNode *cur=head; ListNode *lt,*lt_next,*rt,*rt_next; int count=1; if(m==n) return head; while(cur) { if(m==1) { lt=&tmphead; lt_next=head; } else if(count==m-1) { lt=cur; lt_next=cur->next; } if(count==n) { rt=cur; rt_next=cur->next; } ++count; cur=cur->next; } rt->next=NULL; while(lt_next) { ListNode *tmp=lt_next->next; lt_next->next=rt_next; rt_next=lt_next; lt_next=tmp; } lt->next=rt_next; return tmphead.next; }};
View code
Train of Thought 2: simplify Train of Thought 1. Instead of recording the nodes corresponding to N, directly reverse the linked list through loops;
Code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *lt=NULL; ListNode *lt_next=head; for(int i=0;i<m-1;++i) { lt=lt_next; lt_next=lt_next->next; } ListNode *link; ListNode *link_next=lt_next->next; ListNode *lt_nextsave=lt_next; for(int i=m+1;i<=n;++i) { link=link_next; link_next=link_next->next; link->next=lt_next; lt_next=link; } lt_nextsave->next=link_next; if(lt) lt->next=lt_next; else return lt_next; return head; }};
View code
Reverse Linked List II