- 回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
/**
* 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; }
* }
*/
// 解法一、递归,链表后续遍历,逐个节点比较,时空均为O(n)
// class Solution {
// ListNode left = null;
// public boolean isPalindrome(ListNode head) {
// left = head;
// return isPal(head);
// }
// public boolean isPal(ListNode right) {
// if(right == null) {
// return true;
// }
// boolean res = isPal(right.next);
// res = res && (left.val == right.val);
// left = left.next;
// return res;
// }
// }
// 解法二、迭代,先找到中间节点让后一半反转
// class Solution {
// public boolean isPalindrome(ListNode head) {
// ListNode midNode = findMidNode(head);
// ListNode left = head;
// ListNode right = reverse(midNode.next);
// while (right != null) {
// if (left.val != right.val) {
// return false;
// }
// left = left.next;
// right = right.next;
// }
// return true;
// }
// ListNode findMidNode(ListNode head) {
// ListNode slow = head, fast = head;
// while (fast.next != null && fast.next.next != null) {
// fast = fast.next.next;
// slow = slow.next;
// }
// return slow;
// }
// ListNode reverse(ListNode head) {
// ListNode pre = null, cur = head, next;
// while (cur != null) {
// next = cur.next;
// cur.next = pre;
// pre = cur;
// cur = next;
// }
// return pre;
// }
// }
// 解法三、迭代,找到中间节点的同时让前一半链表反转
// 快慢指针,慢指针反转链表(反转后链表头为pre),另一半链表头为slow,进行逐节点比对
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
ListNode cur = head, pre = null;
while (fast != null && fast.next != null) {
// prepre = pre;
// pre = slow;
// slow = slow.next;
// fast = fast.next.next;
// pre.next = prepre;
slow = cur.next;
fast = fast.next.next;
cur.next = pre;
pre = cur;
cur = slow;
}
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (slow.val != pre.val) {
return false;
}
slow = slow.next;
pre = pre.next;
}
return true;
}
}