还是链表的操作,认真一点就好。在链表前面多加了几个节点,分别是(0)和(-1),方便循环处理和返回结果。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode resultHead = new ListNode(0);
resultHead.next = head;
ListNode tempHead = new ListNode(-1);
tempHead.next = resultHead;
while (tempHead.next.next != null) {
ListNode n = tempHead.next.next;
if (n.next != null) {
tempHead.next.next = n.next;
n.next = n.next.next;
tempHead.next.next.next = n;
} else {
break;
}
tempHead.next = n;
}
return resultHead.next;
}
}