92.反转链表II

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

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

示例:

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        
        ListNode dumy=new ListNode(0);
        dumy.next=head;
        ListNode cur=dumy;
        ListNode pre,last;
        ListNode fron=dumy;
        for(int i=0;i<m-1;i++){
            cur=cur.next;
        }
        pre=cur;
        last=cur.next;
       for(int i=m-1;i<n;i++)
       {
           pre=cur.next;
           cur.next=pre.next;
           pre.next=fron;
           fron=pre;
       }
        pre=cur.next;
        cur.next=fron;
        last.next=pre;
        return dumy.next;
    }
}

猜你喜欢

转载自blog.csdn.net/huanghuansen/article/details/83245871