解题思路
暴力方法:
遍历链表中的每一个元素,依次加入到StringBuffer里,然后利用StringBuffer特有的reverse方法对其进行倒序,最后比较倒序前后的字符串内容是否相同,相同为true,否则为false。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public static boolean isPalindrome(ListNode head) {
if(head == null) return true;
StringBuffer str = new StringBuffer();
while(head!=null) {
str.append(head.val);
head = head.next;
}
return isPalindrome(str);
}
public static boolean isPalindrome(StringBuffer str) {
StringBuffer str2 = new StringBuffer(str);
str.reverse();
//StringBuffer 本身没有equals方法,因为StringBuffer继承object,你使用的equals方法是object的。
if((str.toString()).equals(str2.toString())) {
return true;
}
return false;
}
}