题目:
解法1:双指针
/**
* 思路:
* 遍历链表值存入集合
* 双指针判断回文数
*/
public static boolean isPalindrome(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
return judge_doublePoint(list);
}
private static boolean judge_doublePoint(ArrayList<Integer> list) {
int l = 0, r = list.size() - 1;
while (r > l) {
if (!list.get(l++).equals(list.get(r--))) {
return false;
}
}
return true;
}
时间复杂度:On
空间复杂度:On
解法2:反转链表后半段
01:递归
/**
* 思路:
* 找到链表的中间节点
* 反转链表后半段
* 进行值的比较
*/
public static boolean isPalindrome(ListNode head) {
ListNode slow=head,fast=head;
while (fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
ListNode reverse_half = reverse_recursive(slow);
// ListNode reverse_half = reverse_noPre(slow);
// ListNode reverse_half = reverse_pre(slow);
while (reverse_half!=null){
if (reverse_half.val!=head.val){
return false;
}
reverse_half=reverse_half.next;
head=head.next;
}
return true;
}
private static ListNode reverse_recursive(ListNode head) {
if (head==null||head.next==null){
return head;
}
ListNode tail = reverse_recursive(head.next);
head.next.next=head;
head.next=null;
return tail;
}
时间复杂度:On
空间复杂度:On
02:不设置前驱节点
private static ListNode reverse_noPre(ListNode head) {
ListNode curr = head;
ListNode next = curr.next;
while (next!= null){
ListNode nn = next.next;
next.next=curr;
head.next=nn;
curr=next;
next=nn;
}
return curr;
}
时间复杂度:On
空间复杂度:O1
03:设置前驱节点
private static ListNode reverse_pre(ListNode reversNode) {
ListNode pre=null;
ListNode curr = reversNode;
while (curr!=null){
ListNode next = curr.next;
curr.next=pre;
pre=curr;
curr=next;
}
return pre;
}
时间复杂度:On
空间复杂度:O1
解法3:边找中间节点边反转
/**
* 思路:
* 利用快慢指针找到中间,在这个过程中不断的反转慢指针指向的链表
* 之后不断移动慢指针,比较反转后的节点和慢指针指向的节点的值是否相同
*/
public static boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
ListNode pre=null;
while (fast!=null&&fast.next!=null){
fast=fast.next.next;
ListNode next = slow.next;
slow.next=pre;
pre=slow;
slow=next;
}
if (fast!=null){
slow=slow.next;
}
while (slow!=null){
if (slow.val!=pre.val){
return false;
}
slow=slow.next;
pre=pre.next;
}
return true;
}
时间复杂度:On
空间复杂度:O1