LeetCode-24. Swap Nodes in Pairs

问题描述

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 :

img

1
2
Input: head = [1,2,3,4]
Output: [2,1,4,3]

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* @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
}