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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ? m ? n ? length of list.

C++:
01 /**
02  * Definition for singly-linked list.
03  * struct ListNode {
04  *     int val;
05  *     ListNode *next;
06  *     ListNode(int x) : val(x), next(NULL) {}
07  * };
08  */
09 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         ListNode* prv=NULL;
15         ListNode* hd=NULL;
16         ListNode* end=NULL;
17         ListNode*  start=head;
18         for(int i=1;i<m;i++)
19         {
20             prv=start;
21             start=start->next;
22         }
23         hd=start;
24         end=start->next;
25         for(int i=m;i<n;i++)
26         {
27             ListNode* nextEnd=end->next;
28             end->next=hd;
29             hd=end;
30             end=nextEnd;
31         }
32         start->next=end;
33         if(m>1)
34         {
35             prv->next=hd;
36             return head;
37         }
38         else
39         {
40             return hd;
41         }
42     }
43 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s