回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
package com.LinkList;
public class IsPalindrome5 {
/*
* 思路一:想直接与反转链表进行比较,其中有几个注意点 (1)在进行指针赋值的时候最好不要直接指向别的指针,当同时便利的时候极易出错 (2)这种方法效率很低
*/
// public boolean isPalindrome(ListNode head) {
// ListNode temp1 = new ListNode(head.val);
// ListNode itr = head.next;
// ListNode itr2 = temp1;
// while(itr!=null) {
// itr2.next = itr;
// itr = itr.next;
// }
// ListNode reverse = reverse(head, head.next);
// head.next = null;
// while (temp1 != null && reverse != null) {
// if (temp1.val != reverse.val)
// return false;
// temp1 = temp1.next;
// reverse = reverse.next;
// }
// if (temp1 != null || reverse != null)
// return false;
// return true;
// }
//
// public ListNode reverse(ListNode a, ListNode b) {
// if (b.next == null) {
// b.next = a;
// return b;// 头部
// }
// ListNode tempNext = b.next;
// b.next = a;
// return reverse(b, tempNext);
// }
/*
* 思路二:首先遍历链表得到长度,然后反转一半的链表,在这个过程找到左右指针的起点,需要分奇偶
*/
public boolean isPalindrome(ListNode head) {
ListNode itr = head;
int count = 0;
while (itr != null) {
count++;
itr = itr.next;
}
if (count == 1 || count == 0)
return true;
ListNode itr2 = head;
int c = count % 2 == 0 ? count / 2 : (count / 2 + 1);
System.out.println("c:" + c);
while (c > 0) {
c--;
itr2 = itr2.next;
}
System.out.println(itr2.val + " ");
ListNode reverse = reverse(head, head.next, count / 2 - 1);
while (itr2 != null) {
if (reverse.val != itr2.val)
return false;
reverse = reverse.next;
itr2 = itr2.next;
}
return true;
}
public ListNode reverse(ListNode a, ListNode b, int c) {
if (b == null || c <= 0) {
System.out.println("此时的a:" + a.val);
return a;
}
if (b.next == null) {
b.next = a;
return b;
}
ListNode tempNext = b.next;
b.next = a;
return reverse(b, tempNext, c - 1);
}
}