当前位置:网站首页>力扣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;
}
}边栏推荐
猜你喜欢

PowerCLi import license to vCenter 7

Cocoa Application-test

论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》

SPSS-unary regression practice

Codeforces Round #811 (Div. 3)

Open source summer | Cloud server ECS installs Mysql, JDK, RocketMQ

Ramnit感染型病毒分析与处置

Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错

PowerBI真经连续剧

如何将二叉搜索树转化为一个有序的双向链表(原树上修改)
随机推荐
NFT宝典:你需要知道NFT的术语和定义
Milvus configuration related
rk3399-0.0 svc命令
LocalDateTime的详细使用方法
Lecture 2 Software Life Cycle
y87.第五章 分布式链路追踪系统 -- 分布式链路追踪系统起源(一)
Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错
In which industries is the PMP certificate useful?
论文解读(PPNP)《Predict then Propagate: Graph Neural Networks meet Personalized PageRank》
Oracle使用expdp和impdp导出导入数据
webmine网页挖矿木马分析与处置
Cocoa Application-test
Red team kill-free development practice of simulated confrontation
MySQL查询为啥慢了?
UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd6 in position 120: invalid continuation byte
Excel商业智能-Power BI电商数据分析实战
开源一夏 | 云服务器ECS安装Mysql、JDK、RocketMQ
Win11如何设置软件快捷方式?
Go----Go 语言基础之标识符、关键字、命名规范、变量、常量
搬走地下空间开发利用“绊脚石” 中地数码取得地下空间透明化技术突破