链表的回文问题: 全压栈 与 半压栈

/**
 * 基于栈判断是否为回文
 *      1.使用栈: 所有节点依次入栈,弹出一个与原链表或字符比对有一个不对,不是回文
 *      2.使用栈: 利用快慢指针找到链表中点,以slow下一个开始压入栈中,弹出比对,栈为空停止
 * isPalindrome2()方法使用了快慢指针,我定义的是
 *      slow = head.next();
 *      fast = head.next.next();
 * 其实可以改进为
 *      slow = head;
 *      fast = head;
 * 可以少一次if判断
 */
//遍历链表全部放入栈中,弹出比对
    public static boolean isPalindrome1(Node head){
        if(head == null){
            return false;
        }
        Stack<Node> stack = new Stack<>();
        Node curr = head;
        while (curr != null){
            stack.push(curr);
            curr = curr.next;
        }
        while (head != null){
            if(stack.pop().val != head.val){
                return false;
            }
            head = head.next;
        }
        return true;
    }

    /*
        0 0 0 0 0
          1 1
        基于栈结构,减少一半空间
     */
    public static boolean isPalindrome2(Node head){
        if(head == null){
            return false;
        }
        if(head.next == null){
            return true;
        }
        if(head.next.next == null && head.val != head.next.val){
            return false;
        }
        if(head.next.next != null){
            Node slow = head.next;
            Node fast = head.next.next;
            while (fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            Stack<Node> stack = new Stack<>();
            while (slow.next != null){
                stack.push(slow.next);
                slow = slow.next;
            }
            Node curr = head;
            while (!stack.empty()){
                if(stack.pop().val != curr.val){
                    return false;
                }
                curr = curr.next;
            }
        }

        return true;
    }

 左神算法学习

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值