迭代
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode(-1, head);
ListNode prev = dummyHead;
ListNode cur = head;
/**
* 至少保证剩余两个节点以上
*/
while (cur != null && cur.next != null){
/**
* 保存第三个节点,然后交换前两个节点
* 虚拟头节点指向第二个节点,第二个节点指向第一个节点,第一个节点指向第三个节点
* 更新prev和cur
*/
ListNode temp = cur.next.next;
prev.next = cur.next;
cur.next.next = cur;
cur.next = temp;
prev = cur;
cur = cur.next;
}
return dummyHead.next;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
递归
class Solution {
public ListNode swapPairs(ListNode head) {
/**
* 终止条件
* 节点数目小于2不用交换
*/
if (head == null || head.next == null){
return head;
}
ListNode next = head.next;
/**
* 如果第三个节点,即下一个奇数位节点不为空,则可以进行递归
* 递归完以后,将前两个节点交换并连上
*/
if (head.next != null && head.next.next != null){
next = swapPairs(head.next.next);
ListNode newHead = head.next;
head.next = next;
newHead.next = head;
return newHead;
}
/**
* 如果只剩下两个节点,那就直接交换
*/
head.next = next.next;
next.next = head;
return next;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
优化1——简化递归的判断
class Solution {
public ListNode swapPairs(ListNode head) {
/**
* 终止条件
* 节点数目小于2不用交换
*/
if (head == null || head.next == null){
return head;
}
/**
* 直接从第三个节点开始递归,然后交换前两个节点
*/
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/swap-nodes-in-pairs/