234. Palindrome Linked List
2016-04-14 13:20
260 查看
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?
Linked List Two Pointers
With extra space, add everything to a list first and then compare.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) return true; Deque<Integer> items = new ArrayDeque<Integer>(); ListNode h = head; while(h != null) { items.add(h.val); h = h.next; } while(items.size()>1){ Integer headVal = items.remove(); Integer tailVal = items.removeLast(); if(headVal != tailVal) return false; } return true; } }
O(n) time and O(1) space solution. Split the linked list into to two linked list. One from head to middle, the other from tail to middle.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) return true; int l = -1; ListNode h = head; while(h != null) { ++l; h = h.next; } int middle = l/2; h = head; while(middle>0) { --middle; h = h.next; } ListNode h2 = h.next; h.next = null; //h points to end of first part ListNode tail = revertList(h2); h = head; while(h!=null && tail!= null) { if(h.val != tail.val) return false; h = h.next; tail = tail.next; } return true; } private ListNode revertList(ListNode head) { if(head == null || head.next == null) return head; ListNode h1 = head; ListNode h2 = head.next; while(h2 != null) { ListNode h2next = h2.next; h2.next = h1; h1 = h2; h2 = h2next; } head.next = null; return h1; } }
相关文章推荐
- Android Studio 环境配置优化
- android studio多渠道打包,且根据buildConfig属性判断为哪个渠道升级或者实现不同业务逻辑
- QtCreator:项目中文件按类别放入不同子文件夹
- linux模块导出符号 EXPORT_SYMBOL_GPL EXPORT_SYMBOL
- Android 代码动态改变View的属性
- JDK、Tomcat、ANT及Eclipse常用配置
- LVS Funnat 编译安装使用
- codeforces 660A
- MVC下拉框Html.DropDownList 和DropDownListFor 的常用方法
- 求助:提示错误:warning C206: 'dispay': missing function-prototype
- spring新线程中注入为空指针的问题
- linux字符设备驱动 cdev
- Struts2验证框架 图片验证码 自定义验证器
- Putty实现Linux与Windows互传文件
- One Way Roads(搜索)
- Back to Underworld(搜索)
- ES5中新增的Array方法详细说明
- (五)IBM Sterling OMS 环境构建之环境变量参数配置及语言包
- iOS开发总结之自定义等高cell03-xib
- Yum安装svn及配置