-
Notifications
You must be signed in to change notification settings - Fork 0
/
234. Palindrome Linked List
42 lines (39 loc) · 1.02 KB
/
234. Palindrome Linked List
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
/**
* 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;
if(head.next==null) return true;
ListNode fast = head;
ListNode slow = head;
ListNode reverse = null;
while(fast.next!=null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
head.next = reverse;
reverse = head;
head = slow;
}
slow = slow.next;
if(fast.next == null) {
head = reverse;
}else {
head.next = reverse;
}
//System.out.println(head.val);
while(head !=null && slow !=null) {
if(head.val == slow.val) {
head = head.next;
slow = slow.next;
}
else return false;
}
return true;
}
}