题解 | #链表内指定区间反转#

链表内指定区间反转

http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
  public ListNode reverseBetween (ListNode head, int m, int n) {
        if(m==n) return head;
        ArrayList<Integer> list=new ArrayList<>();
        ArrayList<Integer> list1=new ArrayList<>();
        ListNode current=head;
        while (current!=null){
            list.add(current.val);
            current=current.next;
        }
        for (int i = m-1; i < n; i++) {
            list1.add(list.get(i));
        }
        Collections.reverse(list1);
        int index=0;
        for (int i = m-1; i < n; i++) {
            list.set(i,list1.get(index++));
        }
        current=head;
        int i=0;
        while (current!=null){
            current.val=list.get(i);
            i++;
            current=current.next;
        }
        return head;
    }
}
全部评论

相关推荐

1 1 评论
分享
牛客网
牛客企业服务