难度:medium
Java:
/**
* 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 dummy = new ListNode(-1, head);
ListNode cur = dummy;
ListNode temp1 = null;
ListNode temp2 = null;
while (cur.next != null && cur.next.next != null) {
temp1 = cur.next;
temp2 = cur.next.next;
//注意顺序
cur.next = temp2;
temp1.next = temp2.next;
temp2.next = temp1;
cur = temp1;
}
return dummy.next;
}
}
复杂度分析:
- 时间复杂度:O(n)
- 空间复杂度:O(1)