LeetCode 24. Swap Nodes in Pairs (两两交换链表中的节点)
2024-08-28 20:02:53
题目标签:Linked List
题目给了我们一组 linked list,让我们把每对nodes 互换位置。
新键一个dummy node,然后遍历list,每次建立 s1 和 s2 记录两个点,然后互换位置,具体看code。
Java Solution:
Runtime: 0 ms, faster than 100 %
Memory Usage: 34 MB, less than 100 %
完成日期:05/22/2019
关键点:换位置时候先后顺序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy; while(p.next != null && p.next.next != null) {
ListNode s1 = p.next;
ListNode s2 = p.next.next; // step 1: p -> s2
p.next = s2;
// step 2: s1 -> s2.next
s1.next = s2.next;
// step 3: s2 -> s1
s2.next = s1;
// step 4: p = s1
p = s1;
}
return dummy.next;
}
}
参考资料:LeetCode Discuss
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
最新文章
- hive删除数据
- ubuntu系统自带的火狐(firefox)如何安装Adobe Flash
- 【转】android中最好的瀑布流控件PinterestLikeAdapterView
- DIV+CSS命名规范-转载2
- Linux下VirtualBox出现kernel driver not installed的解决方法
- Pandas之容易让人混淆的行选择和列选择
- Memcache缓存与Mongodb数据库的优势和应用
- Authentication for the REST APIs
- oracle 实例名和服务名以及数据库名区别
- svn 上传 过滤
- POJ 2778 DNA Sequence (AC自动机,矩阵乘法)
- 服务器编程入门(11)TCP并发回射服务器实现 - 单线程select实现
- bootstrap + angularjs + seajs构建Web Form前端(1)
- openlayers 加载瓦片详解 一
- CSS3秘笈:第二章
- 设计模式的征途—1.单例(Singleton)模式
- 3.ubuntu如何安装搜狗输入法
- log4j源码解析
- js--map函数的使用
- Maven classifier 元素妙用
热门文章
- Java——异常的分类
- NX二次开发-Block UI C++界面关于 在Block UI中UF_initialize();和UF_terminate();的使用
- thinkphp5.0多条件模糊查询以及多条件查询带分页如何保留参数
- diji模板
- mkdir无法创建目录权限不够
- C语言——二维数组
- 前端(十四)—— JavaScript常用类:Number、Date类、字符串、数组、Math类、正则
- 一、数据库、SQL简介
- springboot + zipkin + mysql
- 微信app支付返回-1的问题