做题记录:
solution1:把链表内容保存到数组或者list集合中,使用双指针的方法判断
solution2:快慢指针+链表反转+比较的方式判断
附代码:
public static boolean isPalindrome(ListNode head) {
//快慢指针+反转链表
//1 2 3 2 1
//切割之后 1 2 3 / 2 1
//反转之后 1 2 3 / 1 2 或者把后面的放到栈中
//从头开始比较
if (head == null || head.next == null) {
return true;
}
ListNode pre = new ListNode(0, head);
ListNode fast = pre, slow = pre;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode c1 = head, c2 = slow.next;
slow.next = null;
c2 = reverseList(c2);
while (c1 != null && c2 != null) {
if (c1.val != c2.val) {
return false;
}
c1 = c1.next;
c2 = c2.next;
}
return true;
}
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}