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

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    案例:推进GTID解决MySQL主主不同步问题
    idea 每次新建项目都需要重新配置maven的解决方案
    eclipse 配置maven
    maven 配置本地仓库、中央仓库、私库
    eclipse 安装lombok插件(详解)
    plsql 将表结构导出到excel中的两种方式
    ThreadPoolExecutor的用法
    MySQL 5.7 的SSL加密方法
    spring @Async 异步执行
    maven setting 文件配置
  • 原文地址:https://www.cnblogs.com/laydown/p/12838942.html
Copyright © 2011-2022 走看看