标签:
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.
class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { if(!head || m==n ) return head; ListNode * lastOfPrePart = head; ListNode * preReverseNode; ListNode * firstPostPart; ListNode * nextReverseNode; ListNode * currentReverseNode; if(m>1) { for(int i = 0; i < m-2; i++) { lastOfPrePart = lastOfPrePart->next; } currentReverseNode = lastOfPrePart->next; } else { currentReverseNode = head; } nextReverseNode = currentReverseNode->next; firstPostPart = currentReverseNode; for(int i = m; i < n+1; i++ ) { firstPostPart = firstPostPart -> next; } currentReverseNode ->next = firstPostPart; while(nextReverseNode!= firstPostPart) { preReverseNode = currentReverseNode; currentReverseNode = nextReverseNode; nextReverseNode = currentReverseNode->next; currentReverseNode->next = preReverseNode; } if(m!=1) { lastOfPrePart->next = currentReverseNode; } else { head = currentReverseNode; } return head; } };
92. Reverse Linked List II (List)
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4853123.html