LeetCode 234. Palindrome Linked List(对称链表)

20 篇文章 0 订阅
16 篇文章 0 订阅

原题网址:https://leetcode.com/submissions/detail/58253344/

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

思路:普通的思路是可以生成一个反转的链表,然后两个链表逐个节点比较,时间复杂度O(n),空间复杂度O(1)。如果要求空间复杂度O(1)的话,就只能在原链表上做文章了,因为题目并不禁止我们修改原链表,所以我们可以将原链表拆分为前后两段,将前面的反转,然后再逐个比较两段链表的节点。使用慢指针(每次移动一个节点)和快指针(每次移动两个节点),就能够找到链表的中间节点。

慢指针最后停在的位置,就是前段链表拆分后的链表头,后段链表的链表头,需要根据节点个数是奇数还是偶数会有差异,需要分开处理。



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

            ListNode prev = slow;
            slow = next;
            next = next.next;
            slow.next = prev;
        }
        ListNode n1 = slow;
        ListNode n2 = fast.next == null ? next : next.next;
        while (n1 != null) {
            if (n1.val != n2.val) return false;
            n1 = n1.next;
            n2 = n2.next;
        }
        return true;
    }
}


另一个类似的方法:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值