[leetcode]24. Swap Nodes in Pairs交换节点对
2024-10-01 04:11:41
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
题意:
给定一个链表,每两个节点做一下交换。
Solution1: Two Pointers(fast & slow)
(1) use Two Pointers(fast & slow) to find a pair
(2)swap
(3) move forward to find a new pair
code:
/*
Time: O(n)
Space: O(1)
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
head = dummy;
while (head.next != null && head.next.next != null) {
// narrow to find a pair
ListNode slow = head.next;
ListNode fast = head.next.next; // swap
head.next = fast;
slow.next = fast.next;
fast.next = slow; // move to next pair
head = slow;
}
return dummy.next;
}
}
最新文章
- Oracle SQL Developer 连接 MySQL
- Bash:-:-获取未来40天的日期
- Linux shell相关
- NProgress.js template
- App所需申请资料
- Python开发入门与实战4-模板页面
- Xlib 窗口属性
- eclipse Juno Indigo Helios Galileo这几种版本的意思
- jquery JS 左右方向键
- var let const
- 莫烦theano学习自修第七天【回归结果可视化】
- Unable to complete the scan for annotations for web application [/wrs] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies.
- PAT-1001 	采花生
- 八叉树(Octree)
- POJ1734无向图求最小环
- 遇见C++ Lambda
- python3之线程与进程
- iview admin 生成环境打包时路径问题
- js定时执行函数
- 19_AOP概述