题目描述:
解法1:
先通过快慢指针,快指针走2步,慢指针走1步,找到链表中间结点。然后通过头插法翻转后半段链表。然后将前半段链表和后半段链表逐个比较,有不相同返回false,全部相同返回true。
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
ListNode fast = head, slow = head, pre = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
pre.next = null;
slow = fanzhuan(slow);
fast = head;
while(fast != null){
if(fast.val != slow.val) return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode fanzhuan(ListNode head){
ListNode cur = new ListNode(-1);
ListNode pre = null;
while(head != null){
cur.next = head;
ListNode next = head;
head = head.next;
next.next = pre;
pre = next;
}
return cur.next;
}
}
解法2:
首先遍历链表得到链表长度,创建一个和链表长度相同长度的数组。然后再次遍历链表,按次序将链表值写入数组中。在数组中通过首尾双指针的方法,首指针往后移,尾指针往前移,比较两个指针的值。如果有不相同,则返回false,全部相同,则返回true。
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
int count = 0;
ListNode cur = head;
while(head != null){
count++;
head = head.next;
}
int[] number = new int[count];
count = 0;
while(cur != null){
number[count++] = cur.val;
cur = cur.next;
}
int i = 0, j = number.length - 1;
while(i <= j){
if(number[i] != number[j]) return false;
i++; j--;
}
return true;
}
}