[LeetCode]Palindrome Linked List
2015-11-29 09:58
483 查看
反转后一半,然后判断,不过这样子会改变输入的数据,感觉不太好。也可以用一个栈,但是那样的话空间复杂度就不符合标准了。
/** * 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 length = 0; ListNode p = head; while (p != null) { length ++; p = p.next; } p = head; ListNode pre = p; for (int i = 0; i < length / 2; i++) { pre = p; p = p.next; } if (length % 2 == 0) { pre.next = null; p = reverse(p); } else { pre.next = null; p = p.next; p = reverse(p); } while (head != null) { if (head.val != p.val) { return false; } head = head.next; p = p.next; } return true; } public ListNode reverse(ListNode head) { ListNode p2 = head; ListNode p1 = null; while (p2 != null) { ListNode tmp = p2; p2 = p2.next; tmp.next = p1; p1 = tmp; } return p1; } }
相关文章推荐
- (NO.00004)iOS实现打砖块游戏(八):游戏中小球与砖块的碰撞
- (NO.00004)iOS实现打砖块游戏(八):游戏中小球与砖块的碰撞
- (NO.00004)iOS实现打砖块游戏(八):游戏中小球与砖块的碰撞
- 杭电1002——大数求和(双语博客)
- nyoj Splits the string 749 (区间dp)
- 使用JavaScript编程分析多级嵌套JSON文档数据
- 5.10.2 背面剔除
- 20135234马启扬-——信息安全系统设计基础第十二周学习总结
- mysql中的左连接,右连接,内连接,union
- maven pom.xml详解
- javascript实现C语言经典程序题
- hdu 5587(算法之二分)
- android116 轮播 viewPager实现
- 详解js闭包
- 使用 Math 类操作数据
- n皇后问题(回溯法)
- 提高C/C++运行效率以及避免出现Bug的20种方法
- 使用pscp在Linux、Windows间互传文件
- 【Oracle】——Navicat连接Oracle失败
- 百度地图的使用(2)_实现定位功能