【leetcode】92. 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.

 

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseBetween(ListNode* head, int m, int n) {
12         int d=n-m;
13         if(head==NULL||head->next==NULL||d<=0)
14             return head;
15        
16         ListNode* p=head,*bfp=p;
17         ListNode* q=head;
18         for(int i=0;i<m-1;i++){
19             bfp=p;
20             p=p->next;
21         }
22         ListNode* revhead=p;
23         ListNode* bf=p,*bh=NULL;
24         p=p->next;
25         d--;
26         while(p->next!=NULL&&d!=0){
27             d--;
28             bh=p->next;
29             p->next=bf;
30             bf=p;
31             p=bh;
32             
33         }
34         bh=p->next;
35         p->next=bf;
36         bfp->next=p;
37         revhead->next=bh;
38         if(m!=1)
39             return head;
40         else return p;
41     }
42 };

 

posted @ 2016-07-16 21:34  0giant  阅读(256)  评论(0编辑  收藏  举报