【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;
    }
相关推荐
LYFlied4 小时前
【每日算法】LeetCode 19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
踏浪无痕4 小时前
计算机算钱为什么会算错?怎么解决?
后端·算法·面试
消失的旧时光-19434 小时前
从 C 链表到 Android Looper:MessageQueue 的底层原理一条线讲透
android·数据结构·链表
夏乌_Wx5 小时前
练题100天——DAY28:找消失的数字+分发饼干
数据结构·算法
lzh200409195 小时前
二叉搜索树与双向链表
数据结构·链表
studytosky5 小时前
深度学习理论与实战:反向传播、参数初始化与优化算法全解析
人工智能·python·深度学习·算法·分类·matplotlib
WolfGang0073215 小时前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
努力学算法的蒟蒻6 小时前
day35(12.16)——leetcode面试经典150
算法·leetcode·面试
cccc来财6 小时前
角点检测算法:Harris 和 FAST 方法
算法·计算机视觉·特征提取
风中月隐6 小时前
C语言中以坐标的方式图解“字母金字塔”的绘制
c语言·开发语言·算法·字母金子塔·坐标图解法