L24 Swap Nodes in Pairs

LinkedList

Problem:

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
  • should use only constant extra space

  • don't modify the value of the listNode, only node itself can be changed

Solution:

  • call the recursion first, we need to swap head and head.next; head.next.next and it's pairs;

  • by pair

    h

    1 → 2 4 → 3 → 6 → 5 → null

public ListNdoe switchPairs(ListNode head){
    if(head == null || head.next == null) return head;
    
    ListNode subHead = swapPairs(head.next.next);
    head.next.next = head;
    ListNode newHead = head.next;
    head.next = subHead;
    return newHead;
    
}

Last updated

Was this helpful?