Friday, January 29, 2016

LeetCode Q24: Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Surprising to see the difficulty level of this question is marked as "Medium". But it could be this hard if you really try to solve it in an iterative way. Because you gonna be very careful doing many swaps in one iteration.

However, your life will get easier if you try a recursive solution which basically just takes you no more than 10 lines code such as the one in the below:


Solution 2:

No comments:

Post a Comment