File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ Given a singly linked list, determine if it is a palindrome.
2+
3+ ####Follow up:
4+ Could you do it in O(n) time and O(1) space?
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+ public class Solution {
10+ public boolean isPalindrome (ListNode head ) {
11+ if (head == null )
12+ return true ;
13+
14+ Stack <Integer > stack = new Stack <Integer >();
15+
16+ ListNode currNode = head ;
17+ int len = 0 ;
18+
19+ while (currNode != null ) {
20+ stack .push (currNode .val );
21+ currNode = currNode .next ;
22+ len ++;
23+ }
24+
25+ currNode = head ;
26+ int halfLen = len >> 1 ;
27+ for (int i = 0 ; i <= halfLen ; i ++) {
28+ if (currNode .val != stack .pop ()) {
29+ return false ;
30+ }
31+
32+ currNode = currNode .next ;
33+ }
34+
35+ return true ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments