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

234. Palindrome Linked List

时间:2015-11-28 12:06:46      阅读:140      评论: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?

链接: http://leetcode.com/problems/palindrome-linked-list/

题解:

判断链表是否是Palindrome。 我们分三步解,先用快慢指针找中点,接下来reverse中点及中点后部,最后逐节点对比值。

Time Complexity - O(n), Space Complexity - 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) {
        if(head == null || head.next == null)
            return true;
        ListNode mid = findMid(head);
        ListNode tail = reverse(mid);
        mid.next = null;
        
        while(head != null && tail != null) {
            if(head.val != tail.val)
                return false;
            else {
                head = head.next;
                tail = tail.next;
            }
        }
        
        return true;
    }
    
    private ListNode findMid(ListNode head) {               // find mid node of list
        if(head == null || head.next == null)
            return head;
        ListNode slow = head, fast = head;
        
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        
        return slow;
    }
    
    private ListNode reverse(ListNode head) {           // reverse listnode
        if(head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(-1);
        while(head != null) {
            ListNode tmp = head.next;
            head.next = dummy.next;
            dummy.next = head;
            head = tmp;
        }
        return dummy.next;
    }
}

 

Reference

234. Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5002340.html

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