题目
解题思路
画图模拟
(上图是对代码随想录的图进行修改)
代码
/**
* 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 || head.next==null)return head;
ListNode dummy = new ListNode(); //虚拟节点
ListNode pre = dummy;
ListNode cur = head;
while(cur!=null && cur.next!=null){
pre.next = cur.next;
ListNode temp = cur.next.next;
cur.next.next = cur;
cur.next = temp;
pre = cur;
cur = cur.next;
}
return dummy.next;
}
}