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

234. Palindrome Linked List

时间:2017-08-04 18:20:32      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:follow   list   dex   fas   pac   index   bool   ini   逆序   

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;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode index = slow.next;
        ListNode prev = null;
        while (index!= null) {
            
            ListNode temp = index.next;
            index.next = prev;
            prev = index;
            index = temp;
        }
        
        while (prev != null) {
            if (prev.val != head.val) {
                return false;
            }
            prev = prev.next;
            head = head.next;
        }
        return true;
    }
}

  

234. Palindrome Linked List

标签:follow   list   dex   fas   pac   index   bool   ini   逆序   

原文地址:http://www.cnblogs.com/apanda009/p/7286279.html

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