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

Leetcode 92. 反转链表 II

时间:2018-11-10 19:00:52      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:play   reverse   ide   tco   stat   alt   splay   lse   pre   

反转从位置 mn 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

思路:分成两个情况来写
第一种:如果m=1,那就是一道反转链表,先翻转m-n的节点,翻转后,头结点就变成了尾节点,所以把这些节点保存起来,然后再把后面的节点接到尾节点
第二种:如果!=1,翻转m到n的中间节点即可
技术分享图片
 1 public class 反转链表II {
 2     ListNode reverseBetween(ListNode head, int m, int n) {
 3         if(head==null||head.next==null)
 4             return head;
 5         
 6         if(m!=1)
 7         {
 8             ListNode first=head;//记录翻转处的前一个节点
 9             ListNode temp=head.next;//记录尾节点
10             for(int i=0;i<m-2;i++)
11             {
12                 temp=temp.next;
13                 first=first.next;
14             }
15             ListNode la=temp;
16             ListNode pre=temp;//反转的起始节点
17             ListNode p=temp.next;
18             ListNode next=null;
19             for(int i=0;i<n-m;i++)
20             {
21                 next=p.next;
22                 p.next=pre;
23                 pre=p;
24                 p=next;
25             }
26             first.next=pre;
27             la.next=p;
28             
29         }
30         else {
31             ListNode pre=head;
32             ListNode la=pre;
33             ListNode p=head.next;
34             ListNode next=null;
35             
36             for(int i=0;i<n-m;i++)
37             {
38                 next=p.next;
39                 p.next=pre;
40                 pre=p;
41                 p=next;
42             }
43             la.next=p;
44             return pre;//反转后的头结点
45             
46         }
47         
48         return head;
49     }
50     public static void main(String argc[])
51     {
52         
53     }
54 }
View Code

 

Leetcode 92. 反转链表 II

标签:play   reverse   ide   tco   stat   alt   splay   lse   pre   

原文地址:https://www.cnblogs.com/tijie/p/9940155.html

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