LC24. 两两交换链表中的节点

 代码随想录

class Solution {
    // 举例子:假设两个节点 1 -> 2
    // 那么 head = 1; next = 2; next.next = null
    // 那么swapPairs(next.next),传入的是null,再下一次递归中直接返回null
    // 因此 newNode = null
    // 所以 next.next = head; => 2.next = 1; 2 -> 1
    //      head.next=  newNode; => 1.next = null; 1->null
    // 所以 2->1->null
    // 最终返回 next,即返回 2
    public ListNode swapPairs(ListNode head) {
        
        if(head == null || head.next == null)
            return head;

        ListNode next = head.next;

        ListNode newNode = swapPairs(next.next);


        next.next = head;

        head.next = newNode;

        return next;
    }
    
}

相关推荐

  1. LC24. 交换节点

    2023-12-22 08:18:05       48 阅读
  2. leetcode24. 交换节点

    2023-12-22 08:18:05       48 阅读
  3. LeetCode [24] 交换节点

    2023-12-22 08:18:05       44 阅读
  4. 【Leetcode】24. 交换节点

    2023-12-22 08:18:05       44 阅读
  5. LeetCode24.交换节点

    2023-12-22 08:18:05       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-22 08:18:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-22 08:18:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-22 08:18:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-22 08:18:05       20 阅读

热门阅读

  1. 提高Spring Boot技能的9种方法

    2023-12-22 08:18:05       47 阅读
  2. 网络安全-WAF如何判断是攻击行为

    2023-12-22 08:18:05       41 阅读
  3. Docker搭建有分词器的ES集群

    2023-12-22 08:18:05       32 阅读