File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
234-palindrome-linked-list Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## [ 234. Palindrome Linked List] ( https://leetcode.com/problems/palindrome-linked-list/ )
2
+
3
+ | Difficulty | Topics | Acceptance | Total Accepted | Total Submissions |
4
+ | :-: | :-: | --: | --: | --: |
5
+ | Easy | [ Linked List] ( https://leetcode.com/tag/linked-list/ ) , [ Two Pointers] ( https://leetcode.com/tag/two-pointers/ ) | 35.88% | 252.5K | 703.7K |
6
+
7
+ ### Problem:
8
+
9
+ Given a singly linked list, determine if it is a palindrome.
10
+
11
+ ** Example 1:**
12
+
13
+ ```
14
+ Input: 1->2
15
+ Output: false
16
+ ```
17
+
18
+ ** Example 2:**
19
+
20
+ ```
21
+ Input: 1->2->2->1
22
+ Output: true
23
+ ```
24
+
25
+ Follow up:
26
+ Could you do it in O(n) time and O(1) space?
27
+
28
+ | Similar Questions |
29
+ | --- |
30
+ | [ Palindrome Number] ( https://leetcode.com/problems/palindrome-number/ ) |
31
+ | [ Valid Palindrome] ( https://leetcode.com/problems/valid-palindrome/ ) |
32
+ | [ Reverse Linked List] ( https://leetcode.com/problems/reverse-linked-list/ ) |
Original file line number Diff line number Diff line change
1
+ /*-*
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode(int x) { val = x; }
7
+ * }
8
+ */
9
+ class Solution {
10
+ public boolean isPalindrome (ListNode head ) {
11
+ ListNode fast = head , slow = head ;
12
+ while (fast != null && fast .next != null ) {
13
+ fast = fast .next .next ;
14
+ slow = slow .next ;
15
+ }
16
+ if (fast != null ) { // odd nodes: let right half smaller
17
+ slow = slow .next ;
18
+ }
19
+ slow = reverse (slow );
20
+ fast = head ;
21
+ while (slow != null ) {
22
+ if (fast .val != slow .val ) {
23
+ return false ;
24
+ }
25
+ fast = fast .next ;
26
+ slow = slow .next ;
27
+ }
28
+ return true ;
29
+ }
30
+
31
+ public ListNode reverse (ListNode head ) {
32
+ ListNode prev = null ;
33
+ while (head != null ) {
34
+ ListNode next = head .next ;
35
+ head .next = prev ;
36
+ prev = head ;
37
+ head = next ;
38
+ }
39
+ return prev ;
40
+ }
41
+ }
You canβt perform that action at this time.
0 commit comments