Swap Nodes in Pairs

[LeetCode]

https://leetcode.com/problems/swap-nodes-in-pairs/

Total Accepted: 95332 Total Submissions: 270806 Difficulty: Easy

Question

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.

Ways

最讨厌的就是这种指针来回走的题!

先是自己定义了一个头部,然后first指向这个头部answer,然后next指向链表的第一个元素。因为要把前两个元素翻转,所以用after保存第三个元素。

然后就是一系列翻转,我老是搞错。。好囧。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode answer=new ListNode(0);
answer.next=head;
ListNode first=answer;
ListNode next=answer.next;
ListNode after;
while(next!=null && next.next!=null){
after=next.next.next;
next.next.next=next;
first.next=next.next;
next.next=after;
first=next;
next=after;
}
return answer.next;
}
}

AC:1ms

Date

2016/5/1 20:24:22

最新文章

  1. WebGIS项目中利用mysql控制点库进行千万条数据坐标转换时的分表分区优化方案
  2. C语言辗转相除法求2个数的最小公约数
  3. [LeetCode] Valid Parentheses 验证括号
  4. struts.xml
  5. C# 生成windows 服务打包程序
  6. Java 日期格式化工具类
  7. vnc 登录后只有终端 没有桌面 黑屏
  8. LeetCode 笔记28 Maximum Gap
  9. php中命名空间的使用
  10. 轻松大幅度降低 Meteor App 的首屏加载时间
  11. gitignre
  12. debug(fmt,args...)调试
  13. ViewController详解
  14. Linux部署ASP.NET 5 (vNext)
  15. word中批量转换字母数字为Times New Roman
  16. docker 中打包部署Springboot项目
  17. loj.ac:#10024. 「一本通 1.3 练习 3」质数方阵
  18. OGNL表达式的一个坑!
  19. hive数据导出到本地目录 抛异常
  20. 【repost】javascript:;与javascript:void(0)使用介绍

热门文章

  1. distmat 计算遗传距离
  2. R shiny 小工具Windows本地打包部署
  3. Python基础之赋值与注释
  4. cp -拷贝文件出现错误
  5. PC端申请表
  6. python-3.x-生成器使用
  7. A Child's History of England.40
  8. Oracle——生成Awr报告
  9. 哪里可以下载支付宝demo或者sdk
  10. MySQL 迁移到 Redis 记