LeetCode-24. Swap Nodes in Pairs 发表于 2018-04-08 分类于 算法 问题描述Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.) Example : 12Input: head = [1,2,3,4]Output: [2,1,4,3] 解答12345678910111213141516171819202122232425262728293031323334/* * @Description: 24. Swap Nodes in Pairs * @Author: libk * @Github: https://github.com/libk *//** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } *//** * @param {ListNode} head * @return {ListNode} */const swapPairs = function(head) { if (head === null || head.next === null) { return head } let dummy = new ListNode() dummy.next = head let pre = dummy let cur = head while (cur !== null && cur.next !== null) { let temp = cur.next cur.next = temp.next temp.next = pre.next pre.next = temp pre = cur cur = cur.next } return dummy.next}