码迷,mamicode.com
首页 > 编程语言 > 详细

Java [Leetcode 234]Palindrome Linked List

时间:2016-02-06 22:15:19      阅读:177      评论: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?

解题思路:

使用O(n)的时间复杂度及O(1)的时间复杂度表明顺序遍历链表以及不能够开辟跟链表相当的空间,这样可以找出中间的位置,然后将后半部分的链表反转,然后跟前半部分的链表逐个位置比对。

代码如下:

/**
 * 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) {
        ListNode end = head;
        ListNode mid = head;
        while(end != null && end.next != null){
        	end = end.next.next;
        	mid = mid.next;
        }
        if(end != null) //in case of odd list
        	mid = mid.next;
        mid = reverseList(mid);
        while(mid != null){
        	if(mid.val != head.val)
        		return false;
        	mid = mid.next;
        	head = head.next;
        }
        return true;
    }

    public ListNode reverseList(ListNode head){
    	ListNode pre = null, next = null;
    	while(head != null){
    		next = head.next;
    		head.next = pre;
    		pre = head;
    		head = next;
    	}
    	return pre;
    }
}

  

 

Java [Leetcode 234]Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5184345.html

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