Home > Back-end >  What is happening inside this Swap Pairs program
What is happening inside this Swap Pairs program

Time:11-09

I was solving a Leet code question to swap pairs in a linked list. I tried my own solutions and that did not work than I write this dart code from a java solution. I Searched on google but I did not find any explanation. kindly explain it or If I miss some important concept kindly refer me that. I can understand Both Dart and Java explanation.

The code for java is

public ListNode swapPairs(ListNode head) {
    ListNode temp = new ListNode(0);
    temp.next = head;
    ListNode first = head;
    if (head != null && head.next != null) {
      first = head.next;
    }
    while (temp.next != null && temp.next.next != null) {
      ListNode node1 = temp.next;
      ListNode node2 = temp.next.next;
      temp.next = node2;
      node1.next = node2.next;
      node2.next = node1;
      temp = node1;
    }
    return first;
  }

***Dart Code. ***

ListNode? swapPairs(ListNode? head) {
    ListNode temp = new ListNode(0);
    temp.next = head;

    // "first" is pointing to "head"
    ListNode? first = head;
    if (head != null && head.next != null) {
    
      first = head.next;
    }
    while (temp.next != null && temp.next!.next != null) {
      ListNode? node1 = temp.next;
      ListNode? node2 = temp.next!.next;
      temp.next = node2;
      node1!.next = node2!.next;
      node2.next = node1 ;
      temp = node1;
    }
    return first;
  }

We have not done anything to "first" than why are we returning the first and what is happening under the hood.

I am beginner to programming. If you think I should know some concepts, then please refer me that or kindly explain it to me.

CodePudding user response:

First node contains reference to next one aka head of list.

Linked list works something like: Head (First).next -> Second.next -> ... -> Last.next -> null

So returning first node we are actually returning whole list.

CodePudding user response:

You can go off trying to swap pointers. But assuming you are referring to this LeetCode problem, you can simply enumerate the list in pairs and swap the values within the linked list.

public ListNode swapPairs(ListNode head) {
    ListNode temp = head;

    while (temp != null && temp.next != null) {
       int first = temp.val;
       int second = temp.next.val;
       temp.val = second;
       temp.next.val = first;
       temp = temp.next.next;
    }

    return head;
}

The above answer is an accepted solution for the LeetCode link above.

  • Related