LeetCode第234题 回文链表

题目描述

请判断一个链表是否为回文链表。
在这里插入图片描述

解题思路

1、代码1对于链表来,不能直接用双指针同时遍历。如果我们开创一个额外空间,创建一个辅助列表,将链表拷贝到列表中,利用列表的索引来比较。
2、代码2进阶:要求空间复杂度为O(1)
利用快慢指针,同时结合反转。现在简单理解,快指针指到链表的末端,慢指针指到链表的中间,再将后半部分的链表反转。代码没有完全理解,后面再理解
**思路:**将链表切成两段,把后半段反转,然后比较这两段的值是否相等

代码1
/**
 * 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;
        ArrayList<Integer> list = new ArrayList<>();
        ListNode cur = head;

        while(cur != null){
            list.add(cur.val);
            cur = cur.next;
        }
        int lo = 0;
        int hi = list.size() - 1;
        while(lo <= hi){
            if(!list.get(lo).equals(list.get(hi))){
                return false;
            }
            lo++;
            hi--;
        }
        return true}
}
代码2
/**
 * 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 slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

        fast = slow.next;
        slow.next = null;
        return isEqual(head, reverse(fast));

    }
	//把链表反转
    private ListNode reverse(ListNode head){
        ListNode pre = null;
        while(head != null){
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
	//比较两个链表的值是否相等
    private boolean isEqual(ListNode l1, ListNode l2){
        while(l1 != null && l2 != null){
            if(l1.val != l2.val) return false;
            l1 = l1.next;
            l2 = l2.next;
        }
        return true;
    }
}

参考:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-yuan-di-jian-cha-bu-yong-fan-zhu/
https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值