Swap Nodes in Pairs

Swap Nodes in Pairs

https://www.youtube.com/watch?v=f45_eF1gmn8&t=83s




Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.



class Solution {
    public ListNode swapPairs(ListNode head) {
        // base case
        if(head == null || head.next == null){
            // size = 0 , size = 1 
            return head;
        }
        
        // recursion
        ListNode node1 = head.next;
        ListNode next = node1.next;
        node1.next = head;
        head.next = swapPairs(next);
        return node1;
    }
}

// when size = 2, npe won't appear 
// NullPointerException is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.

 

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

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

posted on 2018-08-28 21:23  猪猪🐷  阅读(72)  评论(0)    收藏  举报

导航