Description:
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.
Code:
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
ListNode prev = null;
ListNode newHead = head.next;
while (current != null && current.next != null) {
ListNode first = current;
ListNode second = current.next;
first.next = second.next;
second.next = first;
// check if its not the first pair
if (prev != null) {
prev.next = second;
}
// update pointers
current = second;
prev = current.next;
current = current.next.next;
}
return newHead;
}
}
Questions:
The above code passes all tests, the main struggle was the swapping logic and only after I chose meaningful names first
and second
I was able to clear my thoughts and move forward. Again I see that the linked list involves a lot of edge cases specially managing pointers.
I would like to know if there are some good to know points to avoid common mistakes in linked lists.
PS: Other feedbacks are welcomed too