交换链表中的相邻结点
[!Tip]
本节源代码见Github链接🔗
问题描述
交换链表中的相邻节点,如原链表为1->2->3->4->5,替换为2->1->4->3->5
核心思路
参考12-逐对逆置链表,将链表逐对进行替换,直到遍历到链表末尾
实现代码
【👉🏻>>点击展开查看代码】
/**
* 交换链表中的相邻结点
*
* @param headNode
* @return org.example.linkedlist.normal.NormalListNode
* @author: Max Solider
* @date: 2022/10/12 23:39
*/
NormalListNode exchangeAdjacentNodes(NormalListNode headNode) {
if (headNode == null || headNode.getNext() == null) {
return headNode;
}
NormalListNode current = headNode;
headNode = current.getNext();
while (current != null && current.getNext() != null) {
NormalListNode next = current.getNext();
// 逐对进行交换
NormalListNode temp = next.getNext();
next.setNext(current);
// 需要注意链表结点奇偶性
if (temp != null && temp.getNext() != null) {
current.setNext(temp.getNext());
} else {
current.setNext(temp);
}
current = temp;
}
return headNode;
}
时间复杂度
时间复杂度为O(n),用于遍历链表。
空间复杂度
空间复杂度为O(1),用于存储临时变量。