92. Reverse Linked List II

本文介绍了一种链表中指定区间节点的反转算法实现。通过一次遍历完成m到n位置节点的反转操作,并确保了反转前后的链表连接正确。
 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 }

 

转载于:https://www.cnblogs.com/goPanama/p/9658613.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值