Reverse pairs of elements in a singly-linked list.

Examples

L = null, after reverse is null

L = 1 -> null, after reverse is 1 -> null

L = 1 -> 2 -> null, after reverse is 2 -> 1 -> null

L = 1 -> 2 -> 3 -> null, after reverse is 2 -> 1 -> 3 -> null

Solution: recursion,把head.next.next进行recursion,处理好node间关系

public class Solution {
  public ListNode reverseInPairs(ListNode head) {
    return helper(head);
  }
  private ListNode helper(ListNode head) {
    if (head == null || head.next == null) {
      return head;
    }
    ListNode second = head.next;
    head.next = helper(second.next);
    second.next = head;
    return second;
  }
}

results matching ""

    No results matching ""