234. 回文链表 面试题 02.06. 回文链表

62 篇文章 1 订阅

链接

234. 回文链表
面试题 02.06. 回文链表

解法一

先将链表进行反转,然后对其 val 进行依次判断,不同则返回 false
这里注意:反转的时候要用一个副本来进行反转,否则会对后续判断造成影响

代码

在这里插入图片描述

class Solution {
     public boolean isPalindrome(ListNode head)
    {
        if (head == null || head.next == null)
        {
            return true;
        }

        //head 必不为空,拷贝一个副本用来进行反转
        ListNode cur = head.next;
        ListNode newHead = new ListNode(head.val);
        ListNode newCur = newHead;
        while (cur != null)
        {
            newCur.next = new ListNode(cur.val);
            newCur = newCur.next;
            cur = cur.next;
        }

        //将链表反转
        ListNode pa = head, pb = reverseList(newHead);
        while (pa != null && pb != null)
        {
            if (pa.val != pb.val)
            {
                return false;
            }
            pa = pa.next;
            pb = pb.next;
        }
        return true;
    }
    public ListNode reverseList(ListNode head)
    {
        if (head == null || head.next == null)
        {
            return head;
        }

        ListNode cur = head;
        ListNode prev = null;
        ListNode newHead = null;

        while (cur != null)
        {
            ListNode temp = cur.next;
            cur.next = prev;
            if (temp == null)
            {
                newHead = cur;
            }
            prev = cur;
            cur = temp;
        }
        return newHead;
    }
}

解法二

利用栈先进后出的特性,先将链表中的 val 全部入栈,然后进行出栈并与链表 val 进行比较

代码

在这里插入图片描述

class Solution {
    //用栈操作:栈先进后出,让链表的结点依次入栈
    public boolean isPalindrome(ListNode head)
    {
        if (head == null || head.next == null)
        {
            return true;
        }

        Stack<Integer> stack = new Stack<>();
        ListNode cur = head;
        while (cur != null)
        {
            stack.push(cur.val);
            cur = cur.next;
        }
        //判断
        cur = head;
        while (!stack.isEmpty())
        {
            //出栈
            if (stack.pop() != cur.val)
            {
                return false;
            }
            cur = cur.next;
        }
        return true;
    }
}
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

枳洛淮南✘

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

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

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

打赏作者

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

抵扣说明:

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

余额充值