这个题目非常好。http://blog.csdn.net/u012249528/article/details/47124771给出了三种解法,其中前两个是不满足条件的,不过具有参考价值:

第一种办法:用数组倒着存前半段的链表的值,然后和后半段链表的值进行比较。这种解法运行的时间最久可能是因为数组倒着插入比较耗时。

第二种解法:在第一种的思路的基础上,我们要实现一个倒序,我们干嘛不用现成的数据结构-栈,于是把链表前半段压栈,然后出栈和后面的链表依次比较,这种运行时间最短,但因为用到了栈还是不符合题目要求。

第三种:我们这样想,我们可不可以不借助外在的存储实现倒序呢,其实是可以的,链表反转的时候我们就没有借助外在存储。思路是把后半段的原地链表反转然后和前半段进行比较(当然你也可以反转前半段)运行时间稍微比第二种慢一些,但是符合题目O(1)空间复杂度的要求

本题解决代码参考:https://discuss.leetcode.com/topic/33376/java-easy-to-understand

    public boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
if(head==null||head.next==null){
return true;
}
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller 不用貌似也行
slow = slow.next;
}
//对后半段反转
slow = reverse(slow);
fast = head;
while(slow!=null){
if(fast.val!=slow.val){
return false;
}
fast = fast.next;
slow = slow.next;
}
return true; } public ListNode reverse(ListNode head){
ListNode pre = null;
while(head != null){
ListNode tmp = head.next;
head.next = pre; pre = head;
head = tmp;
}
return pre;
}

最新文章

  1. 支付宝Andfix 原理解析
  2. 两个经典的Oracle触发器示例(轉)
  3. UIActivityIndicatorView添加到UIButton上并响应事件
  4. Ubuntu的LTS版本
  5. linux学习记录(第六章、Linux 的文件权限与目录配置)
  6. python包管理-distutils,setuptools,pip,virtualenv等介绍
  7. Centos中安装Sublime编辑器
  8. Sublime Text 3中配置运行Java
  9. 【20171026早】alert(1) to win - 第六、七、八题
  10. 解决 APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tas
  11. word中中文保持正体,英文用斜体的方法.
  12. shell 之扫描ip段
  13. discuz config_global.php文件设置说明
  14. vue 请求后台数据 (copy)
  15. Windows下使用Git Bash上传项目到GitHub
  16. PHP 循环删除无限分类子节点
  17. ASP.NET MVC4 新手入门教程之九 ---9.查询详情和删除方法
  18. [Codeforces #192] Tutorial
  19. Oracle 版本号说明
  20. Game Develop Books

热门文章

  1. DEV开发之控件NavBarControl
  2. 【leetcode刷题笔记】Unique Binary Search Trees II
  3. python3 mysql 多表查询
  4. 解决COMODO Internet Security更新慢或失败的问题
  5. Spring Cloud之统一fallback接口
  6. 算法(Algorithms)第4版 练习 1.3.7
  7. vue backup
  8. jQuery 开发一个简易插件
  9. JavaScript 使用技巧(持续更新)
  10. el表达式判断字符串相等