File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed
Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+ package easy ;
2+
3+ import java .util .ArrayList ;
4+
5+ public class PalindromeLinkedList234 {
6+
7+ private class ListNode {
8+ int val ;
9+ ListNode next ;
10+
11+ ListNode () {
12+ }
13+
14+ ListNode (int val ) {
15+ this .val = val ;
16+ }
17+
18+ ListNode (int val , ListNode next ) {
19+ this .val = val ;
20+ this .next = next ;
21+ }
22+ }
23+
24+ public boolean isPalindrome1 (ListNode head ) {
25+
26+ ArrayList <Integer > list = new ArrayList <>();
27+ ListNode temp = head ;
28+
29+ while (temp != null ) {
30+ list .add (temp .val );
31+ temp = temp .next ;
32+ }
33+
34+ int front = 0 , back = list .size () - 1 ;
35+
36+ while (front <= back ) {
37+ if (list .get (front ) != list .get (back )) {
38+ return false ;
39+ }
40+ front ++;
41+ back --;
42+ }
43+
44+ return true ;
45+ }
46+
47+ // 2nd approach
48+ // O(N) Time | O(1) Space
49+ public static boolean isPalindrome (ListNode head ) {
50+
51+ ListNode slow = head ;
52+ ListNode fast = head ;
53+
54+ // by the end of this loop, fast will reach end of List & slow to mid of
55+ // List
56+ while (fast .next != null && fast .next .next != null ) {
57+ fast = fast .next .next ;
58+ slow = slow .next ;
59+ }
60+ // reversing the right half of the List
61+ ListNode secondHalfHead = reversed (slow .next );
62+ ListNode firstHalfHead = head ;
63+
64+ // traversing two heads & comparing values
65+ while (secondHalfHead != null && firstHalfHead != null ) {
66+ if (secondHalfHead .val != firstHalfHead .val ) {
67+ return false ;
68+ }
69+
70+ secondHalfHead = secondHalfHead .next ;
71+ firstHalfHead = firstHalfHead .next ;
72+ }
73+ return true ;
74+ }
75+
76+ private static ListNode reversed (ListNode head ) {
77+ ListNode newHead = null ;
78+ while (head != null ) {
79+ ListNode next = head .next ;
80+ head .next = newHead ;
81+ newHead = head ;
82+ head = next ;
83+ }
84+ return newHead ;
85+ }
86+
87+ }
You canβt perform that action at this time.
0 commit comments