PREP54 Editorial

Explanation

  • If first(head) or second element in the linked list is NULL, there will be no swaps so we return the head.
  • We start a while loop to iterate over the linked list until the next two elements are not NULL.
  • We store the pointers to the next two nodes to be swapped in firstNode and secondNode respectively.
  • We change the firstNode’s next value to the value stored in secondNode’s next value.
  • We change the secondNode’s next value to the firstNode.
  • We change the current’s next value to the secondNode.
  • Then we increment current to firstNode.
  • After this loop we return the beginning of the list.