当前位置:网站首页>力扣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;
}
}边栏推荐
猜你喜欢
随机推荐
mysql基础
LeetCode: 406. 根据身高重建队列
27. Dimensionality reduction
【SQL之降龙十八掌】01——亢龙有悔:入门10题
Open source summer | Cloud server ECS installs Mysql, JDK, RocketMQ
As hot as ever, reborn | ISC2022 HackingClub White Hat Summit was successfully held!
The use and principle of CountDownLatch
1319_STM32F103串口BootLoader移植
AtCoder Beginner Contest 262 D - I Hate Non-integer Number
Unknown point cloud structure file conversion requirements
【分布式】分布式ID生成策略
LayaBox---TypeScript---Problems encountered at first contact
PMP证书在哪些行业有用?
Cocoa Application-基础
Arduino 电机测速
智能盘点钢筋数量AI识别
大势所趋之下的nft拍卖,未来艺术品的新赋能
PowerCLi import license to vCenter 7
unity2D横版游戏教程9-对话框dialog
数电快速入门(五)(编码器的介绍以及通用编码器74LS148和74LS147的介绍)









