Swap Nodes in Pairs
Description
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.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Solution(javascript)
function ListNode(val) {
this.val = val
this.next = null
}
const swapPairs = (head) => {
const newHead = new ListNode(0)
newHead.next = head
let current = newHead
while (
current
&& current.next
&& current.next.next
) {
const temp = current.next
current.next = current.next.next
const { next } = current.next
current.next.next = temp
temp.next = next
current = current.next.next
}
return newHead.next
}