【LeetCode】24. Swap Nodes in Pairs(Java)

本文详细介绍了两种在链表中交换相邻节点的算法实现。通过递归和迭代的方法,不改变节点值,仅调整节点链接,完成每对相邻节点的位置交换。提供了完整的Java代码示例,适用于理解链表操作及算法设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:给定一个链表,每交换两个相邻节点并返回其头部。

您不能修改列表节点中的值,只能修改节点本身。

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.

public static ListNode swapPairs(ListNode head) {
        if ((head == null) || (head.next == null))
            return head;
        ListNode Next = head.next;
        head.next = swapPairs(head.next.next);
        Next.next = head;
        return Next;
    }
public static ListNode swapPairs2(ListNode head) {
        if (head == null)
            return null;
        ListNode helper = new ListNode(0);
        helper.next = head;
        ListNode pre = helper;
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            ListNode next = cur.next.next;
            cur.next.next = cur;
            pre.next = cur.next;
            if (next != null && next.next != null)
                cur.next = next.next;
            else
                cur.next = next;
            pre = cur;
            cur = next;
        }
        return helper.next;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值