Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the nodes, only nodes itself may be changed.
To swap pairs of nodes in the given linked list through iteration, simply traverse the entire list. First, define an empty head node, then define the previous node and the current node to be processed. While the current node and its next node exist, cache the current node and the next node. Then, set curNode.next
to nextNode.next
, making the next node the next node of the current node. Next, set preNode.next
to nextNode
, and set nextNode.next
to curNode
. Finally, set preNode
to curNode
, and curNode
to curNode.next
. At this point, curNode
has actually been swapped with the latter node of the two. After the loop is completed, return the next
of the head node.