24.两两交换链表中的节点
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
var swapPairs = function (head) {
if (!head || head.next === null) {
return head
}
let prehead = new ListNode()
let pre = prehead
let cur = head
while (cur && cur.next) {
let node1 = cur
let node2 = cur.next
pre.next = node2
node1.next = node2.next
node2.next = node1
pre = node1
cur = node1.next
}
return prehead.next
};
var swapPairs = function (head) {
let prehead = new ListNode()
prehead.next = head
let cur = prehead
while (cur.next && cur.next.next) {
let node1 = cur.next
let node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
cur = node1
}
return prehead.next
}
var swapPairs = function (head) {
if(!head || !head.next) {
return head
}
let node1 = head
let node2 = head.next
let next = node2.next
node2.next = node1
node1.next = swapPairs(next)
return node2
}