Leetcode 234 Palindrome Linked List

本文介绍了一种在O(n)时间内及O(1)额外空间复杂度下判断单链表是否为回文的方法。通过反转链表前半部分并与后半部分进行比较来实现。代码中详细展示了如何找到链表的中间节点并反转前半部分,最后对比两部分节点值是否相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?


public class Solution234 {
    public boolean compare(ListNode ans1, ListNode ans2) {
        for (; ans2 != null && ans1 != null;ans1 = ans1.next, ans2 = ans2.next) {
            if(ans1.val != ans2.val) {
                return false;
            }
        }

        if(ans1 == null && ans2 == null) {
            return true;
        }

        return false;
    }

    public void print(ListNode tmp) {
        for (; tmp!=null; tmp = tmp.next) {
            System.out.print(tmp.val + " ");
        }
        System.out.println();
    }
    public boolean isPalindrome(ListNode head) {
        int len = 0, position = 0;

        for (ListNode tmp = head; tmp != null; tmp = tmp.next) {
            len++;
        }

        if(len < 2) {
            return true;
        }


        if(len%2 == 0) {
            position = len/2;
        }else {
            position = len/2+1;
        }

        ListNode ans1 = head;

        for (int i = 1; i <= position; i++) {
            ans1 = ans1.next;
        }

        //print(ans1);

        if(len%2 == 1) {
            position -= 1;
        }

        ListNode pre = null, cur =head, next = head;

        for (int i = 0; i < position; i++) {
            next = next.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        cur = pre;

        //print(cur);
        return compare(cur, ans1);
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(1);

        Solution234 ans = new Solution234();

        System.out.println(ans.isPalindrome(head));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值