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

题目

例如: 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 + "  ");
    }
}
posted @ 2018-04-06 18:16  lizhouwei  阅读(143)  评论(0编辑  收藏  举报