[lintcode medium]Palindrome Linked List

检查链表是否为回文
本文介绍了一种算法,用于判断给定的单链表是否为回文结构,在O(n)时间内完成,并且仅使用O(1)的空间复杂度。

Palindrome Linked List

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

Example

Given 1->2->1, return true

Challenge

Could you do it in O(n) time and O(1) space?

 

 

////

1\find out the medium index of Linked list

2\ reverse the right part of linked list in place

3\compare their value;

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a boolean
     */
    public boolean isPalindrome(ListNode head) {
        // Write your code here
        if(head==null || head.next==null) return true;
        if(head.next.next==null)
        {
            if(head.val==head.next.val)
            return true;
            
            else return false;
        }
        
        ListNode fast=head;
        ListNode slow=head;
        
        while(fast.next!=null && fast.next.next!=null )
        {
            fast=fast.next.next;
            slow=slow.next;
        }
        
        ListNode head2=slow.next;
        ListNode pre=null;
        ListNode cur=head2;
        
        slow.next=null;
        while(cur!=null)
        {
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
       
        head2=pre;
        
        ListNode p=head;
        ListNode q=head2;
        while(q!=null)
        {
            if(p.val==q.val)
            {
                p=p.next;
                q=q.next;
            }
            else
             return false;
        }
    
    return true;
        
    }

 

转载于:https://www.cnblogs.com/kittyamin/p/5031674.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值