234.Palindrome Linked List

Linked List, Easy

Question

Given a singly linked list, determine if it is a palindrome.

Example 1:

1
2
Input: 1->2
Output: false

Example 2:

1
2
Input: 1->2->2->1
Output: true

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 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 = head, slow = head;
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//slow -- mid
ListNode tail = reverse(slow);
//compare head->mid, tail->mid if they are the same
while(tail!=null&&head!=null){
if(tail.val!=head.val)
return false;
tail = tail.next;
head = head.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode prev = null;
while(head!=null){
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
//worth mentioning: return prev, when head comes to the end, 'prev=head' prev will get the last node, head will be null
return prev;
}
}

Running time:O(n)