234. Palindrome Linked List
2016-03-14 10:27
239 查看
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?
Subscribe to see which companies asked this question
解析:1.链表分为两段,不管是奇数还是偶数;2.第二段反转一下;3.两段对比一下
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question
解析:1.链表分为两段,不管是奇数还是偶数;2.第二段反转一下;3.两段对比一下
/** * 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; ListNode pre=new ListNode(-1); pre.next=head; ListNode r1=pre; ListNode slow=pre.next,fast=pre.next; while(slow!=null&&fast!=null&&fast.next!=null){ pre=pre.next; slow=slow.next; fast=fast.next.next; } pre.next=null; ListNode head1=r1.next;; ListNode head2=reverse(slow); while(head1!=null&&head2!=null){ if(head1.val!=head2.val) return false; else{ head1=head1.next; head2=head2.next; } } return true; } private ListNode reverse(ListNode head){ if(head==null||head.next==null) return head; Stack<ListNode> stack=new Stack<>(); ListNode pre=new ListNode(-1); ListNode res=pre; ListNode temp=head; while(temp!=null){ stack.push(temp); temp=temp.next; } while(!stack.isEmpty()){ pre.next=stack.pop(); pre=pre.next; } return res.next; } }
相关文章推荐
- .bat文件的编写和运行
- 在windows下将Nginx添加为系统服务
- Android设备抓包命令
- Java并发编程:volatile关键字解析
- linux系统优化
- 多目标跟踪算法
- Android中JNI起源及存在的必要性
- ios app 实现热更新(无需发新版本实现app添加新功能)
- imx6的IOMUX配置方法
- MyEclipse内存参数配置“ -Xms128M -Xmx512M -XX:PermSize=64M -XX:MaxPermSize=128M ”的含义
- iOS获取设备型号、装置类型等信息
- HDU 5297 Y sequence 容斥 迭代
- java学习笔记(一)
- EtherChannel(PAgP、LACP)基本配置
- Python学习
- 【读书笔记】CSS3学习(三)
- 矩阵是否含距离k的重复值
- iOS-常用类继承图详解
- new一个Object对象占用多少内存?
- java 面试题总结