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

234. Palindrome Linked List

时间:2015-07-31 06:36:32      阅读:91      评论: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 || head.next == null) {
      return true;
    }
    // Find the mid element
    ListNode fast = head;
    ListNode slow = head;
    while(fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
    }
    ListNode head2 = slow.next;
    slow.next = null;

    // Reverse second half
    ListNode p1 = head2;
    ListNode p2 = head2.next;
    while(p2 != null && p1 != null) {
      ListNode temp = p2.next;
      p2.next = p1;
      p1 = p2;
      p2 = temp;
    }
    head2.next = null;

    // Compare two parts
    ListNode p = p2 == null? p1: p2;
    ListNode q = head;
    while (p != null) {
      if (p.val != q.val) {
        return false;
      }
      p = p.next;
      q = q.next;
    }
    return true;
  }
}

234. Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/shini/p/4691066.html

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