Skip to content
On this page

24. Swap Nodes in Pairs

https://leetcode.com/problems/swap-nodes-in-pairs/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
  var dummy = new ListNode()
  dummy.next = head
  var current = dummy

  while (current.next && current.next.next) {
    let a = current.next
    let b = current.next.next
    a.next = b.next
    b.next = a
    current.next = b
    current = a
  }

  return dummy.next
}
py
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):

    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(None)
        dummy.next = head
        current = dummy
        while current.next and current.next.next:
            a, b = current.next, current.next.next
            a.next = b.next
            b.next = a
            current.next = b
            current = a
        return dummy.next
go
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
    dummy := &ListNode{
        Next: head,
    }
    current := dummy

    for current.Next != nil && current.Next.Next != nil {
        a := current.Next
        b := current.Next.Next
        a.Next = b.Next
        b.Next = a
        current.Next = b
        current = a
    }

    return dummy.Next
}