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;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    02/Oct/2019:11:55:28 类型的时间转换为
    Flume 实时获取日志内容插入MySQL
    MySQL UTC时间转北京时间 | convert_tz()函数
    使用kettle实现循环
    python 获取系统环境变量 os.environ and os.putenv
    Python
    linux如何判断上一条命令执行是否正确
    局域网两台主机通过网络共享文件
    Kettle(Pentaho)实现web方式远程执行job或transformation
    kettle发送邮件 运行日志
  • 原文地址:https://www.cnblogs.com/laydown/p/12838942.html
Copyright © 2011-2022 走看看