• 《程序员代码面试指南》第二章 链表问题 判断一个链表是否为回文结构


    题目

    例如: 1-2-3-4-4-3-2-1 和 1-2-3-2-1 为回文,1-2-3-4-3-1 不是回文结构
    

    java代码

    /**
     * @Description:  判断一个链表是否为回文结构
     * @Author: lizhouwei
     * @CreateDate: 2018/4/6 17:10
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter2_6 {
    
        public boolean isPalindrome(Node head) {
            if (head == null) {
                return false;
            }
            Node node1 = head;
            Node node2 = head;
            //查找中间节点
            while (node2.next != null && node2.next.next != null) {
                node1 = node1.next;//中间节点
                node2 = node2.next.next;//链表结尾
            }
            node2 = node1.next; //右部分第一个节点
            node1.next = null;
            Node node3 = null;
            //右半区反转
            while (node2 != null) {
                node3 = node2.next;//保存下一个节点
                node2.next = node1;//下一个反转节点
                node1 = node2; //移动
                node2 = node3; //移动
            }
            node3 = node1;//保存原链表最后一个节点,也是反转后右半区第一个节点
            node2 = head;
            boolean res = true;
            while (node1 != null && node2 != null) {
                if (node1.vlaue != node2.vlaue) {
                    res = false;
                    break;
                }
                node1 = node1.next;
                node2 = node2.next;
            }
            //恢复链表
            node1 = node3.next;
            node3.next = null;
            while (node1 != null) {
                node2 = node1.next;
                node1.next = node3;
                node3 = node1;
                node1 = node2;
            }
            //恢复后验证
            Link.printLink(head);
            return res;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_6 chapter = new Chapter2_6();
            Link link = new Link();
            //构造两个链表
            for (int i = 5; i > 0; i--) {
                link.add(i);
            }
            for (int i = 2; i <= 5; i++) {
                link.add(i);
            }
            Link.printLink(link.head);
            boolean bol = chapter.isPalindrome(link.head);
            System.out.println(bol + "  ");
        }
    }
    
  • 相关阅读:
    在centOS上安装oracle出现java.lang.NoClassDefFoundError问题及解决方法
    centos6.5下安装oracle11g
    配置单点登录
    CentOS 环境变量编辑、保存、立即生效的方法
    python如何调用C语言程序
    python生成exe可执行程序
    python的encode()和decode()函数
    python 获取时间
    python修改字符串的值
    python enumerate()函数
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8728411.html
Copyright © 2020-2023  润新知