当前位置:网站首页>力扣24-两两交换链表中的节点——链表
力扣24-两两交换链表中的节点——链表
2022-08-04 21:53:00 【张怼怼√】
题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
求解思路
建立一个虚拟节点指向head,辅助解题;
画图体会链表交换的过程,一切都能解释得通。


输入输出示例

代码
/**
* 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) {
ListNode dump = new ListNode(0);
dump.next = head;
ListNode pre = dump;
while(pre.next != null && pre.next.next != null){
ListNode tem = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = tem;
pre = head;
head = head.next;
}
return dump.next;
}
}边栏推荐
- 基于 Milvus 和 ResNet50 的图像搜索(部署及应用)
- Exploration and Practice of Database Governance
- 传奇服务器需要什么配置?传奇服务器租用价格表
- 关于std::vector<std::string>的操作
- In action: 10 ways to implement delayed tasks, with code!
- 打卡第 1 天:正则表达式学习总结
- ue unreal 虚幻 高分辨率无缩放 编辑器字太小 调整编辑器整体缩放
- docker 部署redis集群
- 打卡第 2 天: urllib简记
- 论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》
猜你喜欢
随机推荐
Excel商业智能-Power BI电商数据分析实战
Yolov7:Trainable bag-of-freebies sets new state-of-the-art for real-time objectdetectors
多个平台显示IP属地,必须大力推行互联网实名制
Cocoa Application-基础
PCBA scheme design - kitchen voice scale chip scheme
Autowired自动装配
数电快速入门(三)(卡诺图化简法的介绍)
Is the International Project Manager PMP certificate worth taking?
rk3399-9.0 first-level and second-level dormancy
LayaBox---TypeScript---structure
Arduino 电机测速
《剑指offer》刷题分类
打卡第 1 天:正则表达式学习总结
Hardware factors such as CPU, memory, and graphics card also affect the performance of your deep learning model
如何在项目中正确使用WebSocket
NFT宝典:你需要知道NFT的术语和定义
unity2D横版游戏教程8-音效
MySQL查询为啥慢了?
The use and principle of CountDownLatch
打卡第 2 天: urllib简记









