Leetcode:234. Palindrome Linked List(JAVA)
2016-03-16 21:19
519 查看
【问题描述】
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、利用栈,将list前半段入栈,然后后半段依次比较出栈。时间复杂度O(N),空间复杂度O(N/2)。
2、将栈的后半段反转,依次比较两端。时间复杂度O(N),空间复杂度O(1)。
【code】
/**
* 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 middle = partition(head);
middle = reverseList(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;
}
// 反转List
private ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode temp = head.next;
ListNode n = reverseList(temp);
head.next = null;
temp.next = head;
return n;
}
}
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、利用栈,将list前半段入栈,然后后半段依次比较出栈。时间复杂度O(N),空间复杂度O(N/2)。
2、将栈的后半段反转,依次比较两端。时间复杂度O(N),空间复杂度O(1)。
【code】
/**
* 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 middle = partition(head);
middle = reverseList(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;
}
// 反转List
private ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode temp = head.next;
ListNode n = reverseList(temp);
head.next = null;
temp.next = head;
return n;
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树