File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=234 lang=java
3
+ *
4
+ * [234] Palindrome Linked List
5
+ *
6
+ * https://leetcode.com/problems/palindrome-linked-list/description/
7
+ *
8
+ * algorithms
9
+ * Easy (35.33%)
10
+ * Total Accepted: 247.5K
11
+ * Total Submissions: 692.5K
12
+ * Testcase Example: '[1,2]'
13
+ *
14
+ * Given a singly linked list, determine if it is a palindrome.
15
+ *
16
+ * Example 1:
17
+ *
18
+ *
19
+ * Input: 1->2
20
+ * Output: false
21
+ *
22
+ * Example 2:
23
+ *
24
+ *
25
+ * Input: 1->2->2->1
26
+ * Output: true
27
+ *
28
+ * Follow up:
29
+ * Could you do it in O(n) time and O(1) space?
30
+ *
31
+ */
32
+ /**
33
+ * Definition for singly-linked list.
34
+ * public class ListNode {
35
+ * int val;
36
+ * ListNode next;
37
+ * ListNode(int x) { val = x; }
38
+ * }
39
+ */
40
+ class Solution {
41
+ public boolean isPalindrome (ListNode head ) {
42
+ if (head == null || head .next == null ) {
43
+ return true ;
44
+ }
45
+
46
+ ListNode prev = null ;
47
+ ListNode slow = head ;
48
+ ListNode fast = head ;
49
+
50
+ while (fast != null && fast .next != null ) {
51
+ fast = fast .next .next ;
52
+ ListNode next = slow .next ;
53
+ slow .next = prev ;
54
+ prev = slow ;
55
+ slow = next ;
56
+ }
57
+
58
+ if (fast != null ) {
59
+ slow = slow .next ;
60
+ }
61
+
62
+ while (slow != null ) {
63
+ if (slow .val != prev .val ) {
64
+ return false ;
65
+ }
66
+ slow = slow .next ;
67
+ prev = prev .next ;
68
+ }
69
+
70
+ return true ;
71
+ }
72
+ }
73
+
You can’t perform that action at this time.
0 commit comments