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

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

Axure9基本交互操作(一)

27. Dimensionality reduction

PyTorch Geometric (PyG) 安装教程

2022年江苏省大学生电子设计竞赛(TI杯)B题 飞机 省级一等奖记录 “一个摆烂人的独白”

ctfshow终极考核web654

SPSS-System Clustering Software Practice

ue unreal 虚幻 高分辨率无缩放 编辑器字太小 调整编辑器整体缩放

Win11如何开启Telnet客户端?

1319_STM32F103串口BootLoader移植
随机推荐
"Jianzhi offer" brush title classification
SPSS-unary regression practice
强网杯2022——WEB
The upgrade and transformation plan of the fortress machine for medium and large commercial banks!Must see!
七夕,当爱神丘比特遇上牛郎和织女
LeetCode 199: 二叉树的右视图
基于声卡实现的音频存储示波器,可作为电磁学实验的测量仪表
看看XDOC如何做Word文档预览
Altium Designer 19.1.18 - 画多边形铜皮挖空时,针对光标胡乱捕获的解决方法
打卡第 1 天:正则表达式学习总结
硬件开发定制全流程解析
SPSS-System Clustering Software Practice
Android 面试——如何写一个又好又快的日志库?
torch单机多卡和多机多卡训练
Oracle增加表空间解决ORACLE ORA-01653: unable to extend table报错
webmine网页挖矿木马分析与处置
Win11如何开启Telnet客户端?
AXI interface application of Zynq Fpga image processing - the use of axi_lite interface
Numpy on the superposition of two arrays
openresty lua-resty-template页面静态化