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

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    tomcat的OutOfMemoryError内存溢出解决方法
    转:动态table分页(ORCALE)
    转: 根据屏幕分辨率,浏览器调用不同css
    转:只能选择GridView中的一个CheckBox(单选CheckBox)
    转:tomcat安全设置
    Tomcat内存设置详解
    Dos命令删除添加新服务
    卸载oracle 10g
    转:oracle:win7手工卸载oracle数据库11g
    win7 下安装oracle 10 g
  • 原文地址:https://www.cnblogs.com/laydown/p/12838942.html
Copyright © 2011-2022 走看看