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:

Given 1->2->3->4, you should return the list as 2->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;
}
}

最新文章

  1. Oracle SQL Developer 连接 MySQL
  2. Bash:-:-获取未来40天的日期
  3. Linux shell相关
  4. NProgress.js template
  5. App所需申请资料
  6. Python开发入门与实战4-模板页面
  7. Xlib 窗口属性
  8. eclipse Juno Indigo Helios Galileo这几种版本的意思
  9. jquery JS 左右方向键
  10. var let const
  11. 莫烦theano学习自修第七天【回归结果可视化】
  12. 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.
  13. PAT-1001 采花生
  14. 八叉树(Octree)
  15. POJ1734无向图求最小环
  16. 遇见C++ Lambda
  17. python3之线程与进程
  18. iview admin 生成环境打包时路径问题
  19. js定时执行函数
  20. 19_AOP概述

热门文章

  1. react hooks 笔记
  2. C#通过代码判断并注册程序集到GAC
  3. python_字符编码&格式化
  4. 随机数的组合问题(JavaScript描述)
  5. cpgf如何实现lua script binding的?
  6. [转]Servlet的学习之Filter过滤器技术
  7. py-day3 python 全局变量和局部变量
  8. C 栈实现队列节点的管理
  9. Microsoft Azure News(7) Azure B系列虚拟机
  10. ubuntu安装nginx及其默认目录结构