【问题描述】
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;
}
}