两两交换链表中的节点
2024年8月25日约 239 字小于 1 分钟
两两交换链表中的节点
题意
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路
常规方法:维护多个指针,遍历一遍链表顺便把每两个节点翻转。
递归方法:利用已有的函数,每两个一组进行递归处理。
代码
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode first = head;
ListNode second = head.next;
ListNode others = head.next.next;
// 先把前两个元素翻转
second.next = first;
// 利用递归,将剩下的链表节点两两翻转,接到后面
first.next = swapPairs(others);
// 现在整个链表都成功翻转了,返回新的头节点
return second;
}
}