24.两两交换链表中的节点
思路1(迭代):
- 设置虚拟头结点,将虚拟头结点指向 此虚拟头结点的 next.next
- 经过步骤1后,将 虚拟头结点的 next 指向 原本未改变时虚拟头结点的next
- 将 原本未改变时虚拟头结点的next 指向 改变后的虚拟头结点的 next.next
- 三个步骤依次循环即可,但要注意有的节点改变后不好取到,所以应提前设置节点保存
代码实现:
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummyHead = new ListNode(-1,head);
ListNode cur = dummyHead;
while (cur.next != null && cur.next.next != null) {
ListNode temp = cur.next;
ListNode temp1 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp;
temp.next = temp1;
cur = cur.next.next;
}
return dummyHead.next;
}
}
思路2(递归):
- 返回值:交换完成的子链表
- 调用单元:设需要交换的两个点为 head 和 next,head 连接后面交换完成的子链表,next 连接 head,完成交换
- 终止条件:head 为空指针或者 next 为空指针,也就是当前无节点或者只有一个节点,无法进行交换
代码实现:
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}