6) Swap Nodes in Pairs

Hi geeks! Today we going to see about how to swap the linked list nodes in a pair wise.

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.


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

Diagrammatic Explanations:


public ListNode swapPairs(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode point = dummy;
    while (point.next != null && point.next.next != null) { 
        ListNode swap1 = point.next;
        ListNode swap2 = point.next.next;
        point.next = swap2;
        swap1.next = swap2.next;
        swap2.next = swap1;
        point = swap1;
    return dummy.next;

Time Complexity : O(n)

Space Complexity: O(n) Since we have used the extra dummy linked list to process.

Leave a Comment

Your email address will not be published. Required fields are marked *