LeetCode -234 - 回文链表 - Java - 三种解法

这题并不难,但是解法多样,所以作者觉得有必要写写!

题目

在这里插入图片描述

那上面例子来说: 就是链表的val值, 从左往右看(1,2,2,1)和 从右往左看(1,2,2,1),都是一样的,就返回true , 否则返回 false。


解法一(快慢指针 + 反转)

先使用快慢指针,得到中间节点,然后反转 中间后半部分 链表节点,然后就是判断回文

代码

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null){
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode cur = slow.next;
        while(cur!=null){
            ListNode curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }
        while(head!=slow){
            if(head.val != slow.val){
                return false;
            }
            if(head.next == slow){
                return true;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }
}

在这里插入图片描述

附图

在这里插入图片描述


解法二 - 通过将链表节点的val值 存入 顺序表/数组 中, 通过数组下标进行对比。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        ListNode currentNode = head;
        while(currentNode != null){
            list.add(currentNode.val);
            currentNode = currentNode.next;
        }
        int front = 0;
        int back = list.size()-1;
        while(front < back){
            if(list.get(front) != list.get(back) ){
                return false;
            }
            front++;
            back--;
        }
        return true;
    }
}

在这里插入图片描述

附图

在这里插入图片描述


解法三 - 递归

递归方法就是效率低了。

代码

class Solution {
    private ListNode frontPointer;
    public boolean isPalindrome(ListNode head) {
        frontPointer = head;
        return recursive(head);
    }
    private  boolean recursive(ListNode currentNode){
        if(currentNode != null){
            if(!recursive(currentNode.next)){
                return false;
            }
            if(currentNode.val != frontPointer.val){
                return false;
            }
            frontPointer =frontPointer.next;
        }
        return true;
    }
}

在这里插入图片描述

附图

在这里插入图片描述

  • 18
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dark And Grey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值