刷题思路来源于 代码随想录
/**
* 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) {
if(head==null){
return null;
}
ListNode dummyHead=new ListNode(-1,head);
ListNode current=dummyHead;
while(current.next!=null&¤t.next.next!=null){
ListNode temp=current.next;
current.next=current.next.next;
temp.next=current.next.next;
current.next.next=temp;
current=current.next.next;
}
return dummyHead.next;
}
}