码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Palindrome Linked List

时间:2016-05-25 07:05:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null){
            return true;
        }
        ListNode mid=findMiddle(head);
        mid.next=reverse(mid.next);
        ListNode p1=head, p2=mid.next;
        while(p2 != null && p1 != null && p1.val == p2.val){
            p1=p1.next;
            p2=p2.next;
        }
        if(p2 == null){
            return true;
        }
        else{
            return false;
        }
        
    }
    public ListNode findMiddle(ListNode head){
        if(head ==null){
            return null;
        }
        ListNode slow=head, fast=head.next;
        while(fast != null && fast.next !=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;
    }
    public ListNode reverse(ListNode head){
        ListNode prev=null;
        while(head != null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }
}

 

LeetCode-Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5525668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!