LeetCode每日一题:回文链表(No.234)

题目:回文链表


请判断一个链表是否为回文链表。
复制代码

示例:


输入: 1->2
输出: false

输入: 1->2->2->1
输出: true
复制代码

思考:


先用快慢指针找到链表中间节点,再将之后的链表反转,反转之后与前半链表节点比较。
复制代码

实现:


class Solution {
public boolean isPalindrome(ListNode head) {
    ListNode slow = head;
    ListNode quick = head;
    while (quick != null && quick.next != null) {
        slow = slow.next;
        quick = quick.next.next;
    }
    ListNode half = slow;
    ListNode reverse = reverse(half);
    while (reverse != null) {
        if (head.val == reverse.val) {
            head = head.next;
            reverse = reverse.next;
        } else {
            return false;
        }
    }
    return true;
}
 public static ListNode reverse(ListNode head) {
    ListNode pre = null;
    ListNode cur = head;
    while (cur != null) {
        ListNode temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}
}复制代码

转载于:https://juejin.im/post/5d09a1956fb9a07f0a2de3e1

猜你喜欢

转载自blog.csdn.net/weixin_34130269/article/details/93168017