示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
const dummy = new ListNode(0);
dummy.next = head;
let current = dummy;
while (current.next != null && current.next.next != null) {
// 初始化双指针
const first = current.next;
const second = current.next.next;
// 更新双指针和 current 指针
first.next = second.next;
second.next = first;
current.next = second;
// 更新指针
current = current.next.next;
}
return dummy.next;
};
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""
用递归实现链表相邻互换:
第一个节点的 next 是第三、第四个节点交换的结果,第二个节点的 next 是第一个节点;
第三个节点的 next 是第五、第六个节点交换的结果,第四个节点的 next 是第三个节点;
以此类推
:param ListNode head
:return ListNode
"""
# 如果为 None 或 next 为 None,则直接返回
if not head or not head.next:
return head
_next = head.next
head.next = self.swapPairs(_next.next)
_next.next = head
return _next
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
next := head.Next
head.Next = swapPairs(next.Next) // 剩下的节点递归已经处理好, 拼接到前 2 个节点上
next.Next = head
return next
}
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution
{
/**
* @param ListNode $head
* @return ListNode
*/
function swapPairs($head)
{
if (!$head || !$head->next) return $head;
/** @var ListNode $next */
$next = $head->next;
$head->next = (new Solution())->swapPairs($next->next); // 递归已经将后面链表处理好, 拼接到前面的元素上
$next->next = $head;
return $next;
}
}
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode h, *tail = &h;
while (head && head->next) {
auto p = head, q = head->next;
head = q->next;
q->next = p;
tail->next = q;
tail = p;
}
tail->next = head;
return h.next;
}
};