文章目录
一、题目
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
二、遇到的问题
1. 什么时候用单指针,什么时候用双指针?
2. 为什么需要设置虚拟头结点?
- 最终需要通过虚拟头结点来返回整个链表
- 便于操作链表
3. 如何交换相邻的两个节点?
cur——》1——》2——》3——》4
实现思路:
cur——》2——》1——》3——》4
在执行的过程中需要通过 temp 来暂存 1,通过 temp1 来暂存 3,防止连接断裂
当交换下一组相邻的两个节点(3、4)时,cur 指向 1(待交换的节点的前一个位置)
4. 为什么 cur 要指向要交换的两个节点的前一个节点?
保持连接不断裂。让交换后的这两个节点仍然连接在链表中。
5. 什么时候结束交换?
当最后没有节点,或者最后只剩下单个节点。即 cur.next == null; 或 cur.next.next == null
三、代码
public class Solution {
public ListNode swapPairs(ListNode head) {
// 虚拟头结点
ListNode dummy = new ListNode(-1, head);
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
// 暂存待交换的两个节点中的前一个节点
ListNode temp = cur.next;
cur.next = cur.next.next;
// 暂存待交换的两个节点后的那个节点
ListNode temp1 = cur.next.next;
cur.next.next = temp;
cur.next.next.next = temp1;
cur = cur.next.next;
}
return dummy.next;
}
}
class ListNode {
// 链表的值
int val;
// 节点的指针
ListNode next;
// 无惨构造函数
public ListNode() {
}
// 带参构造函数
public ListNode(int val) {
this.val = val;
}
// 节点构造函数
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}