码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode92 Reverse Linked List II

时间:2016-01-06 17:57:32      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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

 

leetcode92 Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/jsir2016bky/p/5106008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!