LeetCode234——回文链表

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/palindrome-linked-list/description/

题目描述:

知识点:链表

思路:快慢双指针遍历链表,再将后半部分链表翻转

关于反转链表函数的实现,请见LeetCode206——反转链表

时间复杂度是O(n),其中n为链表中的节点数。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur2 = dummyHead;
        ListNode cur3 = dummyHead;
        while(cur3 != null && cur3.next != null) {
            cur2 = cur2.next;
            cur3 = cur3.next.next;
        }
        cur2 = cur2.next;
        ListNode preCur2 = dummyHead;
        while(preCur2.next != cur2) {
            preCur2 = preCur2.next;
        }
        preCur2.next = null;
        ListNode newHead = reverseLinkedList(cur2);
        ListNode cur = head;
        ListNode newCur = newHead;
        while(cur != null && newCur != null) {
            if(cur.val != newCur.val) {
                return false;
            }
            cur = cur.next;
            newCur = newCur.next;
        }
        return true;
    }
    private ListNode reverseLinkedList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = cur.next;
        while(cur != null) {
            cur.next = pre;
            pre = cur;
            cur = next;
            if(cur != null) {
                next = cur.next;
            }
        }
        return pre;
    }
}

LeetCode解题报告:

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值