File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change 1+ public class ListNode {
2+ int val ;
3+ ListNode next ;
4+ ListNode () {}
5+ ListNode (int val ) { this .val = val ; }
6+ ListNode (int val , ListNode next ) { this .val = val ; this .next = next ; }
7+ }
Original file line number Diff line number Diff line change 1+ import java .util .Stack ;
2+
3+
4+ // my solution
5+ public class PalindromeLinkedLIst {
6+ public static void main (String [] args ) {
7+ ListNode list = new ListNode (1 , new ListNode (0 ,new ListNode (1 )));
8+ System .out .println (new PalindromeLinkedLIst ().isPalindrome (list ));
9+ }
10+
11+ public boolean isPalindrome (ListNode head ) {
12+ Stack <Integer > stack = new Stack <>();
13+ ListNode head2 = head ;
14+ int cnt = isCount (head2 );
15+
16+ if (cnt == 1 )
17+ return true ;
18+
19+ for (int i = 0 ;head != null ; i ++){
20+ if (cnt % 2 == 1 && cnt /2 == i ){
21+ head = head .next ;
22+ continue ;
23+ }
24+
25+ if (stack .isEmpty ()) {
26+ stack .push (head .val );
27+ head = head .next ;
28+ continue ;
29+ }
30+ if (stack .peek () != head .val )
31+ stack .push (head .val );
32+ else
33+ stack .pop ();
34+
35+ head = head .next ;
36+ }
37+
38+ return stack .isEmpty ();
39+ }
40+
41+ public int isCount (ListNode listNode ){
42+ int cnt =0 ;
43+ while (listNode != null ){
44+ cnt ++;
45+ listNode = listNode .next ;
46+ }
47+ return cnt ;
48+ }
49+ }
50+
51+ /* best solution_USE REVERSE
52+ public boolean isPalindrome(ListNode head) {
53+ ListNode fast = head, slow = head;
54+ while (fast != null && fast.next != null) {
55+ fast = fast.next.next;
56+ slow = slow.next;
57+ }
58+ if (fast != null) { // odd nodes: let right half smaller
59+ slow = slow.next;
60+ }
61+ slow = reverse(slow);
62+ fast = head;
63+
64+ while (slow != null) {
65+ if (fast.val != slow.val) {
66+ return false;
67+ }
68+ fast = fast.next;
69+ slow = slow.next;
70+ }
71+ return true;
72+ }
73+
74+ public ListNode reverse(ListNode head) {
75+ ListNode prev = null;
76+ while (head != null) {
77+ ListNode next = head.next;
78+ head.next = prev;
79+ prev = head;
80+ head = next;
81+ }
82+ return prev;
83+ }
84+ */
You can’t perform that action at this time.
0 commit comments