amazon o2 - reverse second half linked list

public ListNode reverseBetween(ListNode head, int m, int n) {
  if(head==null) return head;
  ListNode slow = head;
  ListNode fast = head;

  //find middle
  while(fast.next!=null) {
    fast = fast.next;
    if(fast.next!=null) {
      fast = fast.next;
    }
    else {
      slow = slow.next;
    }
  }
  ListNode current = slow.next;
  ListNode halfFirst = current;
  if(current == null || current.next==null) {
    return head;
  }
  ListNode next = current.next;

  // reverse
  while(next!=null) {
    ListNode temp = current;
    current = next;
    next = next.next;
    current.next = temp;
  }

  //combine
  slow.next = current;
  halfFirst.next = null;
  return head;
}

你可能感兴趣的:(amazon o2 - reverse second half linked list)