leetcode 234: Palindrome Linked List
2016-03-25 12:43
309 查看
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?
[思路]
先分成大小同样(可能长度差1) 两部分, reverse一个list. 再比較.
[CODE]
Follow up:
Could you do it in O(n) time and O(1) space?
[思路]
先分成大小同样(可能长度差1) 两部分, reverse一个list. 再比較.
[CODE]
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ // 1 2 3 2 1; 1 2 3 3 2 1; public class Solution { public boolean isPalindrome(ListNode head) { //input check abcba abccba if(head==null || head.next==null) return true; ListNode middle = partition(head); middle = reverse(middle); while(head!=null && middle!=null) { if(head.val != middle.val) return false; head = head.next; middle = middle.next; } return true; } private ListNode partition(ListNode head) { ListNode p = head; while(p.next!=null && p.next.next!=null) { p = p.next.next; head = head.next; } p = head.next; head.next = null; return p; } private ListNode reverse(ListNode head) { if(head==null || head.next==null) return head; ListNode pre = head; ListNode cur = head.next; pre.next = null; ListNode nxt = null; while(cur!=null) { nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } return pre; } }
相关文章推荐
- JQuery判断页面是否按下了Enter键
- Win7下使用Telnet命令
- Unity发布时出现“The type or namespace name `UnityEditor' could not be found.” 错误
- SQL语句中 and or执行优先级
- hdu 1241 Oil Deposits (BFS)
- 图片压缩总结
- 关于Eclipse自动补全的问题
- Ubuntu 使用中遇到的小问题(持续更新)
- 【转】KVM/Installation
- 客户端发一个post请求
- 深拷贝的现代写法
- OMS开发(二):技术选型
- Jquery常用radio取值,checkbox取值,select取值,radio选中,checkbox选中,select选中,及其相关设置
- 启动调试时总是提示此项目已经过期的解决方案
- 坑爹的prototype
- 22.推送多条只显示一条问题
- Dubbo基础篇_03_简单的Dubbo提供者provider与消费者consumer
- Java中的基本数据类型 | Java基础
- unsigned int与int相加问题
- 20160226.CCPP体系详解(0036天)