判断一个链表是否回文(每日一道算法题)

回文:就是正序输出和逆序输出的顺序一致。
给出了两种方式(原来有三种,第三种太复杂,被我pass了)

package LinkedList;

import java.util.Stack;

/**
 * @author:MindMrWang
 *2017年12月4日
 *:function:
 */
public class isPalindrome {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(1);

        node1.next = node2;
        node2.next = node3;

        System.out.println(isPalinderome2(node1));
    }
    //使用栈来判别是否会文,将链表节点放入栈中,然后将栈中节点取出和链表进行比对
    public static boolean isPalinderome1(Node head) {
        Node cur = head;
        Stack<Node> stack = new Stack<Node>();
        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;
    }

    //方法二,对方法一的改进,只需要将后一半的链表放入栈即可,然后和前一半的链表值进行比对
    public static boolean isPalinderome2(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<Node>();

        while(right != null) {
            stack.push(right);
            right = right.next;
        }

        while(!stack.isEmpty()) {
            if(stack.pop().value != head.value) {
                return false;
            }
            head = head.next;
        }
        return true;
    }
}

参考书籍《程序员代码面试指南》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值