Swap nodes in pairs

problem [https://leetcode.com/problems/swap-nodes-in-pairs/ 24. Swap Nodes in Pairs].

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


 * Example 1
 * Input: head = [1,2,3,4]
 * Output: [2,1,4,3]
 * Example 2
 * Input: head = []
 * Output: []
 * Example 3
 * Input: head = [1]
 * Output: [1]


 * Constraints
 * The number of nodes in the list is in the range.


 * Follow up:Can you solve the problem without modifying the values in the list's nodes? (i.e., Only nodes themselves may be changed.)

Iterative approach
The iterative approach means that we traverse the linked list from left to right, and reverse a pair of nodes during each iteration.

For each iteration, we can use two pointers   and   to mark the two elements to be swapped, and additional two pointers   and   to mark the locations of  and   on the next iteration.

The iteration looks like this;

Loop until  reaches null. This happens when either:
 * If the total number of nodes is even, both  and   have reached the end (become  ); or
 * If the total number is odd,  has reached the end (becomes null).

Time complexity
So the total time complexity is O(n).
 * For n total nodes there are (n/2) iterations.
 * Each iteration performs the job in O(1) time.

Space complexity
So the space complexity is O(1).
 * On the stack we only store four pointers:,  ,  ,.
 * We do not need to allocate additional objects on heap.

Recursive approach
The recursive approach means that we reverse the first two nodes of the entire list, and then the first two nodes of the sublist starting at the 3rd element, and then first two nodes of the sublist starting at the 5th element… and so on.

The recursion is as follows:
 * Base case: A sublist with zero (null) or one node is not reversed. Return the head of the sublist directly.
 * Recursive case: Reverse the first two nodes. Then recursively apply the procedure to the sublist starting from the third node.

Time complexity

 * For n total nodes we have n/2 levels of recursions.
 * Each level of recursion swaps the first two nodes of the sublist.

So the total time complexity must be O(n).

Space complexity

 * Stack: Each time we allocate pointers  and   to swap the first two elements. In each recursion two such pointers are used.
 * So the space complexity on stack is O(n).


 * Heap: We did not allocate additional memory on heap. So the space complexity on heap is O(1).

The total space complexity is O(n).