反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseBetween(ListNode head, int m, int n) { 11 ListNode firstend = null; 12 ListNode secondend = null; 13 ListNode secondstart = null; 14 ListNode thirdstart = null; 15 ListNode iterator = head; 16 ListNode pre = null; 17 ListNode next = null; 18 int i=1; 19 int reverseFlag = 0; 20 if(n==m){ 21 return head; 22 } 23 while(iterator!=null){ 24 next=iterator.next; 25 if(reverseFlag==0){ 26 if(i==m){ 27 firstend = null; 28 secondend=iterator; 29 pre=iterator; 30 reverseFlag=1; 31 } 32 else if(i+1==m){ 33 firstend = iterator; 34 reverseFlag=1; 35 } 36 }else{ 37 if(i<n){ 38 if(i==m){ 39 secondend=iterator; 40 }else{ 41 iterator.next=pre; 42 } 43 pre=iterator; 44 }else if(i==n){ 45 iterator.next=pre; 46 secondstart=iterator; 47 if(next==null){ 48 thirdstart=null; 49 }else{ 50 thirdstart=next; 51 } 52 break; 53 } 54 } 55 i++; 56 iterator=next; 57 } 58 if(firstend!=null){ 59 firstend.next=secondstart; 60 }else{ 61 head=secondstart; 62 } 63 if(thirdstart!=null){ 64 secondend.next=thirdstart; 65 }else{ 66 secondend.next=null; 67 } 68 return head; 69 } 70 }
笔记:将链表看作了三部分,中间部分是需要反转的,三部分分别标记为first,second,third。(注意一些边界情况,比如第一部分和第二部分都可能为空,还有当m等于n时直接返回即可)。