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 ≤ m ≤ n ≤length of list.
The [M,n] that section to pull out, after reverse, then spell back.
The main consideration is the boundary conditions.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */structnode{ListNode*Head; ListNode*tail; Node (ListNode* Begin, listnode*end): Head (Begin), tail (end) {}};classSolution { Public: ListNode*reversebetween (ListNode *head,intMintN) {//Find beginlistnode* tail =Head; ListNode* cur =Head; ListNode* begin =NULL; ListNode* end =NULL; ListNode* Pre =NULL; intTMP =m; while(--tmp)//--tmp{Pre=cur; Cur= cur->Next; } Begin=cur; TMP= Nm; while(tmp--)//tmp--Cur = cur->Next; End=cur; while(Tail->next! =NULL) Tail= tail->Next; //4 Cases if(Begin = =head) {//Result->head is head if(End = =tail) { //reverse all, return Result->headnode* result =reverse (begin, end); Result->tail->next =NULL; returnResult->Head; } Else { //reverse from head to end, End->next=post, and return Result->headlistnode* post = end->Next; End->next =NULL; Node* result =reverse (begin, end); Result->tail->next =Post; returnResult->Head; } } Else {//Head is head if(End = =tail) { //reverse from begin to tail, Pre->next = Result->head, and return headnode* result =reverse (begin, end); Pre->next = result->Head; Result->tail->next =NULL; returnHead; } Else { //reverse from begin to end, Pre->next = begin, End->next = post, and return headlistnode* post = end->Next; End->next =NULL; Node* result =reverse (begin, end); Pre->next = result->Head; Result->tail->next =Post; returnHead; }}} Node* Reverse (listnode* begin, listnode*end) {Node* result =NewNode (begin, end); if(Begin = =end)returnResult//No change Else if(Begin->next = =end) {End->next =begin; Begin->next =NULL; Result->head =end; Result->tail =begin; returnresult; } Else{ListNode* Pre =begin; ListNode* cur = pre->Next; ListNode* Post = cur->Next; while(Post! =NULL) {cur->next =Pre; Pre=cur; Cur=Post; Post= post->Next; } cur->next =Pre; Begin->next =NULL; Result->head =cur; Result->tail =begin; returnresult; } }};
"Leetcode" Reverse Linked List II