Palindrome Linked List
Input: 1->2
Output: falseInput: 1->2->2->1
Output: trueAnalysis
1 -> 1 -> 2 -> 1 -> null
sf1 -> 1 -> 2 -> 1 -> null
s fSolution
Reference
Last updated
Input: 1->2
Output: falseInput: 1->2->2->1
Output: true1 -> 1 -> 2 -> 1 -> null
sf1 -> 1 -> 2 -> 1 -> null
s fLast updated
1 -> 1 null <- 2 <- 1
h s1 -> 1 null <- 2 <- 1
h s/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast, slow;
fast = head;
slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) {
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while (fast != null && slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode tmpNext = curr.next;
curr.next = prev;
prev = curr;
curr = tmpNext;
}
return prev;
}
}public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
slow = reverse(slow);
while (head != null && slow != null) {
if (head.val != slow.val) {
return false;
}
head = head.next;
slow = slow.next;
}
return true;
}