92. Reverse Linked List II

 1 class Solution {
 2     public ListNode reverseBetween(ListNode head, int m, int n) {
 3         ListNode node1 = head;
 4 //        int len = 0;             //可以不用加
 5 //        while(node1 != null) {
 6 //            len++;
 7 //            node1 = node1.next;
 8 //        }
 9 //        if(len == 1) return head;
10 //        node1 = head;
11         ListNode pre = null;
12         for(int i = 1; i <= m - 1; i++) {
13             pre = node1;
14             node1 = node1.next;    
15         }
16         ListNode last = head;
17         for(int i = 1; i <= n; i++) {
18             last = last.next;
19         }
20         node1 = head;
21         ListNode record = node1;
22         int count = 1;
23         while(count <= n) {
24             if(count >= m) {
25                 record = node1.next;
26                 node1.next = last;
27                 last = node1;
28                 node1 = record;
29                 if(count == n) {
30                     if(pre != null) {  //注意要判断pre是不是null
31                         pre.next = last;
32                     }else {
33                         head = last;
34                     }    
35                 }
36             }else {
37                 node1 = node1.next;
38             }
39             count++;
40         }
41         return head;
42         
43         
44     }
45 }

 

posted @ 2018-09-17 01:01  jasoncool1  阅读(87)  评论(0编辑  收藏  举报