【leetcode-链表】 回文链表

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

思路:利用快慢指针找到中间节点,当快指针走到末尾时, 慢指针指向中间节点;交中间节点之后的节点进行链表反转; 设定指针p1从head开始, p2从中间节点下一节点开始, 逐个比较,如果有不相等则不是回文,如果都相等,则是回文。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null)
        return true;
    ListNode fast = head;
    ListNode slow = head;
    while (fast.next != null && fast.next.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    ListNode reverseHead = reverseList(slow.next);

    while (head != null && reverseHead != null) {
        if (head.val != reverseHead.val)
            return false;
        head = head.next;
        reverseHead = reverseHead.next;
    }
    return true;
}

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null)
        return head;
    ListNode p = null;
    ListNode q;
    while (head != null) {
        q = head.next;
        head.next = p;

        p = head;
        head = q;
    }
    return p;
}

}
发布了196 篇原创文章 · 获赞 212 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/kangbin825/article/details/105022764