【題目】
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?
【思路】
panlidrome的話,迴文,就是前後是一樣的。第一個和最後一個一樣, 第二個和倒數第二個一樣。
linked list的話,首先要明確不能回退。如果我使用two pointers的話,一個指針再頭,一個指針在最後是不可行。。
思路一: 使用stack
遍歷兩 遍linkedlist. 第一遍,將所有元素放入到Stack中。
第二遍遍歷,就是將棧內的元素彈出來然後進行對比。
time: O(n);
space: O(n)
但是!!題目有加要求O(1)!!怎麼辦呢
【代碼】
/**
* 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)
{
Stack<Integer> s = new Stack<Integer>();
ListNode temp = head;
ListNode cur = head;
while(temp != null)
{
s.push(temp.val);
temp = temp.next;
}
while(cur != null)
{
if(cur.val != s.peek())
return false;
else
{
cur = cur.next;
s.pop();
}
}
return true;
}
}
space: O(1)並沒有特別好想的方法。。。
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) {
return true;
}
ListNode p1 = head;
ListNode p2 = head;
ListNode p3 = p1.next;
ListNode pre = p1;
//find mid pointer, and reverse head half part
while(p2.next != null && p2.next.next != null) {
p2 = p2.next.next;
pre = p1;
p1 = p3;
p3 = p3.next;
p1.next = pre;
}
//odd number of elements, need left move p1 one step
if(p2.next == null) {
p1 = p1.next;
}
else { //even number of elements, do nothing
}
//compare from mid to head/tail
while(p3 != null) {
if(p1.val != p3.val) {
return false;
}
p1 = p1.next;
p3 = p3.next;
}
return true;
}
}