CTCI 2.7

Implement a function to check if a linked list is a palindrome.

Reverse the second half of the list and then compare it with the first half.

/* Assume that we can destroy the list, reverse the second half of the list and compare it with the first
half. If we were not permit to destroy the list, change the list to an array and then check if it is a 
palidrome.
*/

public class IsPalidrome {
    public boolean isPalidrome(Node head) {
        if(head == null || head.next == null) return true;
        int cnt = 0;
        Node temp = head;
        while(temp != null) { cnt++; temp = temp.next; }
        int half = cnt / 2;
        temp = head;
        while(half > 1) { temp = temp.next; half--; }
        Node sent = new Node(0);
        //break the list into two parts
        Node temp1 = temp.next, temp2 = temp.next; temp.next = null; 
        //reverse the second half
        while(temp1 != null) {
            temp2 = temp1.next;
            temp1.next = sent.next;
            sent.next = temp1;
            temp1 = temp2;
        }
        //check if it is palidrome
        Node head1 = head, head2 = sent.next;
        while(head1 != null && head2 != null) {
            if(head1.val == head2.val) {
                head1 = head1.next;
                head2 = head2.next;
            }
            else return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Node node1 = new Node(1); Node node11 = new Node(1); node1.next = node11;
        Node node2 = new Node(1); Node node22 = new Node(2); node2.next = node22;
        Node node31 = new Node(1); Node node32 = new Node(2); Node node33 = new Node(1); node31.next = node32; node32.next = node33;
        Node node41 = new Node(1); Node node42 = new Node(3); Node node43 = new Node(2); Node node44 = new Node(1);
        node41.next = node42; node42.next = node43; node43.next = node44;
        IsPalidrome ip = new IsPalidrome();
        System.out.println(ip.isPalidrome(node1));
        System.out.println(ip.isPalidrome(node2));
        System.out.println(ip.isPalidrome(node31));
        System.out.println(ip.isPalidrome(node41));
    }
}

 

转载于:https://www.cnblogs.com/pyemma/p/3832439.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值