zoukankan      html  css  js  c++  java
  • 判断一个链表是否是回文结构


    import java.util.Stack;

    /**
    * 判断一个链表是否是回文结构
    */
    public class IsPalindrome {

    /**
    * 将整个链表放入栈中,依次弹出并和原链表比较,相当于直接把链表反转然后比较,若完全相同则为回文结构
    *
    * @param head 链表头结点
    * @return 是否回文结构
    */
    public boolean isPalindrome(Node head) {
    if (head == null || head.next == null) {
    return true;
    }
    Stack<Node> stack = new Stack<>();
    Node cur = head;
    while (cur != null) {
    stack.push(cur);
    cur = cur.next;
    }
    while (head != null) {
    if (head.value != (stack.pop().value)) {
    return false;
    }
    head = head.next;
    }
    return true;
    }

    /**
    * 给定链表,奇数长度则取中点下一个节点,偶数长度则取下中点,从该节点依次入栈,并从链表头部开始比较,若相同则为回文结构
    *
    * @param head 链表头结点
    * @return 是否回文结构
    */
    public boolean isPalindrome2(Node head) {
    if (head == null || head.next == null) {
    return true;
    }
    Node right = head.next;
    Node cur = head;
    while (cur.next != null && cur.next.next != null) {
    right = right.next;
    cur = cur.next.next;
    }
    Stack<Node> stack = new Stack<>();
    while (right != null) {
    stack.push(right);
    right = right.next;
    }
    while (!stack.isEmpty()) {
    if (head.value != (stack.pop().value)) {
    return false;
    }
    head = head.next;
    }
    return true;
    }

    /**
    * 给定链表,奇数长度则取中点下一个节点,偶数长度则取下中点,从该节点反转链表,将得到的两个链表依次从头开始遍历比较,若相同,则为回文结构
    * 注:比较完成之后需要将链表还原
    *
    * @param head 链表头结点
    * @return 是否回文结构
    */
    // public boolean isPalindrome3(Node head) {}

    /**
    * 链表结构
    */
    public static class Node {

    public int value;

    public Node next;

    public Node(int value) {
    this.value = value;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    Windows下PHP开启mcrypt扩展和SSL(OpenSSL)扩展支持
    MyBatis 学习笔记
    试用百度云计算平台
    TCP三次握手及四次挥手详细图解
    Java开发中的23种设计模式详解
    Extjs4.1.0_从入门到精通
    SQLite3命令操作大全
    带你了解 HBase 数据模型和 HBase 架构
    让数据库无惧灾难,华为云GaussDB同城双集群高可用方案正式发布!
    论文阅读丨神经清洁: 神经网络中的后门攻击识别与缓解
  • 原文地址:https://www.cnblogs.com/laydown/p/12838942.html
Copyright © 2011-2022 走看看