首先说明回文:如:"灵山大佛,佛大山灵","客上天然居,居然天上客"等等,都是美妙的符合正念倒念都一样的回文句。
回文数则是有类似22、383、5445、12321,不论是从左向右顺读,还是从右向左倒读,结果都是一样的特征。
在数组中{ 1, 2, 5, 8, 6, 8, 5, 2, 1 }, { 2, 5, 2 }, { 2 }等都是回文。
- 首先,要判断是否是回文PalindromeList,要得到数组的长度,因此,写一个getLength类来得到长度。
public int getLength(ListNode head) {
int count =0;
ListNode cur = head;
while(cur != null) {
cur = cur.next;
count++;
}
return count;
}
- 因为回文是对称的,所以要得到数组的中间数,思路是从中间将它分为俩个数组,然后俩个数组的值进行比较,如果俩个数组完全相等,则该数组为回文,否则,就不是。用一个getMiddle类来得到中间数。
public ListNode getMiddle(ListNode head) {
int length = getLength(head);
int half = length / 2;
ListNode cur = head;
for(int i = 0; i < half; i ++){
cur = cur.next;
}
return cur;
}
- 因为是对称结构,所以从中间分成俩个数组时,后一个数组直接就是一个数组,只需要找一个头节点链上即可,而前一个数组则需要从后往前链,即逆置链表。用reserveList类来逆置数组。
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode nHead =null;
ListNode next =cur.enxt;
while(cur != null) {
cur.next = nHead;
nHead = cur;
cur = next;
}
return nHead;
}
4.最后,判断是否是回文,返回一个boolean值,此时就需要调用 getLength 和 reverseList 方法来对传进来的数组进行处理 ,最后判断。
public boolean chkPalindrome(ListNode A) {
ListNode middle = getMiddle(A);
ListNode rHead = reverseList(middle);
ListNode c1 = A;
ListNode c2 = rHead;
while(c1 != null && c2 != null) {
if(c1.val != c2.val) {
return false;
}
c1 = c1.next;
c2 = c2.next;
}
return true;
}
这样,就判断出一个数组是否是回文结构。
判断一个数是不是回文
这里在简单说一下判断一个数是不是回文结构,这个应该相对简单一点。这里的思路是,如果是负数,肯定不是回文;判断一个大于0的数的时候,首先将这个数逆置,然后和原来的数取比较,如果相同,那么就是回文了,反之则不是。代码也比较简单。
public boolean isPalindrome(int x) {
if(x < 0)
return false;
int cur = 0;
int y = x;
while(y != 0) {
cur = cur * 10 + y % 10;
y /= 10;
}
return cur == x;
}