翻转链表II

来源:互联网 发布:耐克马拉松鞋矩阵 编辑:程序博客网 时间:2024/06/15 17:11

翻转链表中第m个节点到第n个节点的部分

 注意事项

m,n满足1 ≤ m ≤ n ≤ 链表长度

样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null


/** 
 * Definition for ListNode 
 * public class ListNode { 
 *     int val; 
 *     ListNode next; 
 *     ListNode(int x) { 
 *         val = x; 
 *         next = null; 
 *     } 
 * } 
 */
 /*
 思路:
    1.先让head走到m的前一个结点,让end走到n的下一个结点
    2.翻转链表
 
 */
public class Solution {  
    public ListNode reverseBetween(ListNode head, int m , int n) {  
        // write your code  
        ListNode dummy = new ListNode(0);  
        dummy.next = head;  //!!!
        //使得head到达m的前一个结点(前)  
        head = dummy;  
        for(int i=0;i<m-1;i++){  
            head=head.next;  
        }  
        //使得end到达n的下一个结点  
        ListNode end = dummy; //!!! 
        for(int i=0;i<n+1;i++){  
            end=end.next;  
        }  
        
        //reverse  
        ListNode pre = end;  
        ListNode cur = head.next;  
        while(cur!=end){  
            ListNode next = cur.next;//保存当前结点的下一个结点
            cur.next = pre;  //翻转
            //向后移
            pre = cur;  
            cur = next;  
        }  
        head.next = pre;  
        return dummy.next;  
    }


}