leetcode92 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         ListNode *ans=head;
13         ListNode *pri=head;
14         int count=n-m;
15         if(m==1)
16             ans=NULL;
17         else
18             ans=head;
19         if(m==1)
20         {
21             ListNode *rev=pri;
22             ListNode *acc=rev->next;
23             ListNode *revlast=rev;
24             while(count--)
25             {
26                 ListNode *temp=acc;
27                 acc=acc->next;
28                 temp->next=rev;
29                 rev=temp;
30             }
31             revlast->next=acc;
32             ans=rev;
33         }
34         else
35         {
36             m--;
37             while(--m)
38                 pri=pri->next;
39             
40             ListNode *rev=pri->next;
41             ListNode *acc=rev->next;
42             ListNode *revlast=rev;
43             while(count--)
44             {
45                 ListNode *temp=acc;
46                 acc=acc->next;
47                 temp->next=rev;
48                 rev=temp;
49             }
50             revlast->next=acc;
51             pri->next=rev;
52         }
53         return ans;
54     }
55 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5106008.html