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

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    netty的ChannelPipeline执行顺序对inBound和outBound执行器造成的影响
    【转载,并做少量修改整合】Java 双亲委派模型与应用:SPI(Service Provider Interface)
    JDK1.8 论ConcurrentHashMap是如何扩容的
    如何解决Vue.js里面noVNC的截图问题之后篇——用web虚拟终端作为替代功能
    hihocoder 1036 Trie图
    Codeforces#390
    Codeforces#386
    codeforces 743D Chloe and pleasant prizes
    codeforces 742E (二分图着色)
    洛谷 P1280 尼克的任务题解
  • 原文地址:https://www.cnblogs.com/laydown/p/12838942.html
Copyright © 2011-2022 走看看