题目描述
题目连接24. 两两交换链表中的节点
题解
链表题舍得用指针就好
- 首先建个哑节点res。 res.next = head;
- 要交换两个相邻节点,需要保存3个指针,1、前驱节点pre;2、第一个要交换的节点slow; 3、第二个要交换的节点fast。交换过程如下:
pre.next = fast;
slow.next = fast.next;
fast.next = slow;
- 更新pre,交换下一组
详见代码注释
class Solution {
public ListNode swapPairs(ListNode head) {
//没有节点或者只有一个节点,直接返回
if (head == null || head.next == null) return head;
//新建哑节点,简化处理
ListNode res = new ListNode();
res.next = head;
//要交换的两个节点的前驱节点
ListNode pre = res;
while (pre.next != null && pre.next.next != null){
//交换slow和fast
ListNode fast = pre.next.next, slow = pre.next;
pre.next = fast;
slow.next = fast.next;
fast.next = slow;
//更新前序节点,反转下一组
pre = slow;
}
return res.next;
}
}