当前位置: 首页 > news >正文

leetcode 两两交换链表中的节点 java

两种方法:递归法和迭代法。
我首先想到的是迭代,因为我不会用递归。
如果觉得很绕的话,直接把节点都定义出来。

class Solution {public ListNode swapPairs(ListNode head) {ListNode dummy = new ListNode(0,head);ListNode cur = dummy;// while(cur.next.next!=null){while(cur.next!=null && cur.next.next!=null ){// ListNode temp = cur.next;// cur.next=cur.next.next;// cur.next.next=temp;// temp.next=cur.next.next.next;// cur=cur.next.next;ListNode temp1 = cur.next;ListNode temp2 = cur.next.next;cur.next=temp2;temp1.next=temp2.next;temp2.next=temp1;cur=temp1;          }return dummy.next;}
}

递归法:参考了Leetcode评论区大神的方法,很直白!

/*** Definition for singly-linked list.* public class ListNode {*     int val;*     ListNode next;*     ListNode() {}*     ListNode(int val) { this.val = val; }*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {//递归if(head == null || head.next==null){return head;}ListNode one = head;ListNode two = head.next;ListNode three = head.next.next;//one.next=three;two.next=one;one.next=swapPairs(three);return two;}
}
http://www.xdnf.cn/news/622693.html

相关文章:

  • 【R语言科研绘图】
  • 讯飞AI相关sdk集成springboot
  • Matlab实战训练项目推荐
  • LangGraph-agent-天气助手
  • 自然语言处理核心技术:词向量(Word Embedding)解析
  • 【读代码】BAGEL:统一多模态理解与生成的模型
  • 服务器硬盘虚拟卷的处理
  • 如何合法使用代理IP?
  • HTTP协议初认识、速了解
  • 奇好 PDF安全加密 + 自由拆分合并批量处理 OCR 识别
  • 记录python在excel中添加一列新的列
  • 【系统设计】2WTPS生产级数据处理系统设计Review
  • 大数据如何让智能物流和仓储管理更高效?从预测到自动调度
  • 【AI实战】从“苦AI”到“爽AI”:Magentic-UI 把“人类-多智能体协作”玩明白了!
  • 超详细网络介绍(超全)
  • YOLOv8损失函数代码详解(示例展示数据变换过程)
  • 如何对轨迹进行减速并保证在原来的轨迹上面
  • Python应用字符串格式化初解
  • [CSS3]Flex布局
  • C++中IO类(iostream、fstream和sstream)知识详解和应用
  • 负载均衡笔记
  • webpack的构建流程
  • 持续集成和部署
  • 每日Prompt:梦回大唐
  • uniapp判断ios或Android定位是否开启并跳转到系统设置
  • 老字号如何逆龄生长?解码数字突围战
  • 5.24本日总结
  • 高效大型语言模型推理优化综述
  • 怎么开发一个网络协议模块(C语言框架)之(三) 全局实例
  • 基于pycharm,python,flask,sklearn,orm,mysql,在线深度学习sql语句检测系统