[LeetCode 234] Palindrome Linked List
2015-08-18 14:38
471 查看
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Solution:
1. Reverse later half part
2. two pointer go through list, one from front and end
Follow up:
Could you do it in O(n) time and O(1) space?
Solution:
1. Reverse later half part
2. two pointer go through list, one from front and end
public boolean isPalindrome(ListNode head) { if(head ==null || head.next == null) return true; //get middle node, ListNode l1 = head; ListNode l2 = head; while(l2.next!=null){ l1 = l1.next; if(l2.next.next == null){ l2 = l2.next; break; } l2 = l2.next.next; } //reverse linked list l2 = l1.next; while(l2!=null) { ListNode l3 = l2.next; l2.next = l1; l1 = l2; l2 = l3; }//l1 is the last one //two pointer from front and end l2 = head; while(l2 != l1 && l2.next!=l1){ if(l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } if(l2.next == l1) return l2.val == l1.val; return true; }
相关文章推荐
- iOS UICollectionView简单使用
- 360浏览器默认以兼容模式或急速模式方式打开页面
- iOS开发中如何获取设备唯一标识
- MVC 之 Ajax 分页查询数据
- iOS 初始化 懒加载
- code-blocks 中文乱码解决
- (C#)Winform修改DateTimePicker控件的背景色
- ftp客户端代码
- 删除android ScrollView边界阴影方法
- IOS Core Data框架初探
- 曾经的笔记迁移__二维数组
- 13 面向对象编程 - 《Python 核心编程》
- Code First 数据注释
- 剑指offer相关问题
- 数据申请方法梳理
- 深入理解Java虚拟机
- JDK及tomcat配置
- jquery 验证
- 曾经的笔记迁移__指针
- eclipse 如何把java项目转成web项目