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

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

1. 对应力扣题目连接

  • 两两交换链表中的节点

2. 实现案例代码

public class ExchangeLinkedListsPairwise {public static void main(String[] args) {// 示例链表:[1, 2, 3, 4]ListNode head = new ListNode(1);head.next = new ListNode(2);head.next.next = new ListNode(3);head.next.next.next = new ListNode(4);// 迭代方法ListNode swapPairsIterative = swapPairsIterative(head);printList(swapPairsIterative); // 输出:[2, 1, 4, 3]}// 迭代方法实现public static ListNode swapPairsIterative(ListNode head) {// 创建一个虚拟头节点ListNode dummy = new ListNode(0);dummy.next = head;ListNode prev = dummy;while (head != null && head.next != null) {ListNode firstNode = head;ListNode secondNode = head.next;// 交换节点prev.next = secondNode;firstNode.next = secondNode.next;secondNode.next = firstNode;// 更新指针prev = firstNode;head = firstNode.next; // 移动到下一个未交换的节点}return dummy.next;}public static void printList(ListNode head) {ListNode current = head;while (current != null) {System.out.print(current.val + " ");current = current.next;}System.out.println();}}class ListNode {public int val;public ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}
}
http://www.lryc.cn/news/390746.html

相关文章:

  • java设计模式(四)——抽象工厂模式
  • 动物检测yolo格式数据集(水牛 、大象 、犀牛 、斑马四类)
  • 昇思25天学习打卡营第05天 | 数据变换 Transforms
  • Springboot+MySQL 公寓报修管理系统源码
  • jenkins 发布服务到linux服务器
  • Appium+python自动化(三十九)-Appium自动化测试框架综合实践 - 代码实现(超详解)
  • 防止跨站脚本攻击XSS之Antisamy
  • Python爬虫实战案例——王者荣耀皮肤抓取
  • PyTorch计算机视觉实战:目标检测、图像处理与深度学习
  • 4D 生物打印:将时间维度融入,打造个性化动态组织
  • 银行清算业务功能测试解析
  • CVE-2024-6387漏洞预警:尽快升级OpenSSH
  • 学习整理在php中使用PHPExcel读取excel表列数大于Z时读取不到的解决方案
  • python sklearn机械学习-数据预处理
  • 搜索引擎常用语法
  • 华为智能驾驶方案剖析
  • DDR3(一)
  • Eureka与Spring Cloud Bus的协同:打造智能服务发现新篇章
  • Kafka入门到精通(三)-Kafka
  • 高校教师教学质量评估系统-计算机毕业设计源码03344
  • 币界网讯,预计以太坊现货 ETF 将于 7 月中旬推出
  • 【FFmpeg】avio_open2函数
  • 技术成神之路:设计模式(二)建造者模式
  • 基于Springboot+Vue+mysql仓库管理系统仓库进销存管理系统
  • 爬虫scrapy库精简使用大全
  • Qt - 如何在新线程 (QThread)中使用一个进程 (QProcess)?
  • Qt绘制多线段
  • 去中心化革命:探索区块链技术的前沿
  • 2024年湖南省各市科小申报时间(科技型中小企业申报流程、条件、好处)新政
  • 【JD-GUI】MacOS 中使用Java反编译工具JD-GUI