【链表】Swap Nodes in Pairs(三指针)
2024-08-26 18:56:35
题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:
给链表添加一个临时的头结点, 这样操作更方便。其实大部分链表问题,添加一个头结点,都会简化后面的操作
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
var tempHead=new ListNode(0);
tempHead.next=head;
var pre=tempHead,p=head; while(p&&p.next){
pre.next=p.next;
p.next=p.next.next;
pre.next.next=p; pre=p;
p=p.next;
} return tempHead.next;
};
最新文章
- mongodb指南
- 个人对JQuery Proxy()函数的理解
- yii 图片展示
- 用户上网的基本流程图与DNS解析原理
- 【翻译】24款界面精美的免费UI工具包
- 【风马一族_Android】通过菜单的点击,跳转到不同界面
- Arraysort
- Golang分布式爬虫:抓取煎蛋文章|Redis/Mysql|56,961 篇文章
- hive配置过程中出现的一个问题
- 新概念英语(1-73)The way to King Street
- RxJava系列7(最佳实践)
- Redis设置Key的过期时间 – EXPIRE命令
- APPCORE Routine APIs
- x64类型的程序逆向思考
- Jenkins关闭和重启实现方式.
- Ubuntu 安装google 拼音
- 左连接,右连接,内连接(left join ,right join,inner join)
- jQuery-iframe加载完成后触发的事件监听
- CentOS 6.5 下源码搭建LAMP环境
- JVM(三)JVM的ClassLoader类加载器
热门文章
- springmvc 开涛 数据验证
- Java菜鸟学习笔记(23)--继承篇(二):继承与组合
- 关于CI/CD/CD (Continuous Integration/Continuous Delivery/Continuous Deployment)
- Python 数据结构与算法——冒泡排序
- subprocess.Popen 运行windows命令出现“句柄无效”报错的解决方法
- CentOS7查看CPU个数
- NLayerAppV3-Infrastructure(基础结构层)的Data部分和Application(应用层)
- Spring Boot 学习系列(10)—SpringBoot+JSP的使
- Delphi - 让Delphi10.2在Windows下开发的图形界面程序运行在64位Linux中!
- Python3.5 学习八