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?
這道題看的答案,第一種解法是構(gòu)造一個原鏈表的reversed LinkedList, 然后再一一比較元素是否相等。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null){
return true;
}
ListNode p = head;
ListNode prev = new ListNode(head.val);
while (p.next != null){
ListNode temp = new ListNode(p.next.val);
temp.next = prev;
prev = temp;
p = p.next;
}
while (head != null){
if (head.val != prev.val){
return false;
}
head = head.next;
prev = prev.next;
}
return true;
}
}
第二種方法是將LinkedList截成兩端,然后將后半段reverse. 再比較前半段和reversed后半段是否一致來確定是不是回文串
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null){
return true;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode secondHalf = slow.next;
slow.next = null;
ListNode p1 = secondHalf;
ListNode p2 = p1.next;
while (p1 != null && p2 != null){
ListNode temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}
//Crucial step, or linkedlist could be circular
secondHalf.next = null;
//do not know the situation when p2 != null
ListNode p = p1;
ListNode q = head;
while (q != null && p != null){
if (q.val != p.val){
return false;
}
q = q.next;
p = p.next;
}
return true;
}
}