234. Palindrome Linked List

Given the head of a singly linked list, return true if it is a palindrome.

Example 1:
Input: head = [1,2,2,1]
Output: true

Example 2:
Input: head = [1,2]
Output: false

Constraints:
The number of nodes in the list is in the range [1, 105].
0 <= Node.val <= 9

Follow up: Could you do it in O(n) time and O(1) space?

Solution:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reverse(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
}
public boolean isPalindrome(ListNode head) {
if (head.next == null) {
return true;
}
if (head.next.next == null) {
return head.val == head.next.val;
}
ListNode middle = head, rBegin = head;
while (rBegin.next != null) {
if (rBegin.next.next != null) {
middle = middle.next;
rBegin = rBegin.next.next;
} else {
rBegin = rBegin.next;
}
}
reverse(middle.next);
ListNode left = head;
ListNode right = rBegin;
boolean res = true;
while (right != null) {
if (left.val != right.val) {
res = false;
break;
} else {
left = left.next;
right = right.next;
}
}
return res;
}
}

references

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×