forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpalindromeLinkedList.java
More file actions
42 lines (37 loc) · 879 Bytes
/
palindromeLinkedList.java
File metadata and controls
42 lines (37 loc) · 879 Bytes
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
/*
Given a singly linked list, determine if it is a palindrome.
https://leetcode.com/problems/palindrome-linked-list/
*/
/**
* 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 slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode last = slow.next;
ListNode pre = head;
while (last.next != null) {
ListNode temp = last.next;
last.next = temp.next;
temp.next = slow.next;
slow.next = temp;
}
while (slow.next != null) {
slow = slow.next;
if (pre.val != slow.val) return false;
pre = pre.next;
}
return true;
}
}