解法一:模拟
注意指针更新顺序。
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode swapPairs(ListNode head) {ListNode root = new ListNode(0, head);// 待交换结点的前一个结点ListNode last = root;// 第一个待交换结点ListNode first = head;// 第二个待交换结点ListNode second;while ((first != null) && (first.next != null)) {// 交换结点second = first.next;last.next = second;first.next = second.next;second.next = first;// 更新指针last = first;first = first.next;}return root.next;}}
