链表的回文判断—Java实现

对于这个题,主要是老是局限于方法内的变量,未想到借助外部变量辅助:具如下,不可用数除法,会溢出异常:即使是取最大的long也会溢出,常规方法不再赘述,具体以代码如下:

 1 package ProblemSolve;
 2 
 3 public class Solution5 {
 4     private ListNode frontNode;
 5     public boolean isPalindrome(ListNode head) {
 6         StringBuilder stringBuilder = new StringBuilder();
 7         while (head != null) {
 8             stringBuilder.append(head.val);
 9             head = head.next;
10         }
11         String str=new String(stringBuilder);
12         String strReverse=new String(stringBuilder.reverse());
13         return str.equals(strReverse);
14     }
15     public boolean isPalindrome2(ListNode head) {
16 ;       frontNode=head;
17         return reverseList(head);
18     }
19     public boolean reverseList(ListNode head){
20         if (head!=null){
21             if (!reverseList(head.next))
22                 return false;
23             if (head.val!=frontNode.val)
24                 return false;
25             frontNode=frontNode.next;
26         }
27         return true;
28     }
29 }

没写注释抱歉!!

 

posted @ 2023-04-07 23:06  Mexcellent  阅读(36)  评论(0)    收藏  举报