![]()
1 /**
2 * Definition for singly-linked list.
3 * public class ListNode {
4 * int val;
5 * ListNode next;
6 * ListNode() {}
7 * ListNode(int val) { this.val = val; }
8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 * }
10 */
11 class Solution {
12 public ListNode swapPairs(ListNode head) {
13 // 增加头节点
14 ListNode root = new ListNode(0);
15 // 新建头节点连接到入参链表
16 root.next = head;
17 // 申请临时节点-交换临时节点后面的两个节点
18 ListNode temp = root;
19 // 开始交换
20 while (temp.next != null && temp.next.next != null) {
21 // 记录要交换的左节点
22 ListNode node1 = temp.next;
23 // 记录要交换的右节点
24 ListNode node2 = temp.next.next;
25 // 交换左右节点
26 temp.next = node2;
27 node1.next = node2.next;
28 node2.next = node1;
29 // 移动临时节点-用于继续交换下一对节点
30 temp = node1;
31 }
32 // 返回结果
33 return root.next;
34 }
35 }