【leetcode-两两交换链表中的节点】

迭代法

java 复制代码
  public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode result = new ListNode(0);
        result.next=head;
        ListNode curr = result;
        while(curr.next !=null && curr.next.next!=null){
            ListNode next = head.next;
                    ListNode tmp = next.next;

                    curr.next=next;
                    next.next=head;
                    head.next=tmp;

                    curr=head;
                    head=head.next;
        }
        return result.next;
    }

递归法

java 复制代码
    public 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;
    }
相关推荐
在所不辞兄2 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
无忧.芙桃4 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
文丑颜不良啊6 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI7 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊7 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz38999 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子1312 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法