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

[LC] 234. Palindrome Linked List

时间:2019-12-31 12:46:25      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:head   tno   nod   list   bool   output   rom   link   NPU   

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        
        // get middle node
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode mid = slow;        
        
        // revert from mid next
        mid.next = revert(mid.next);
        ListNode aNode = head;
        ListNode bNode = mid.next;
        while(aNode != null && bNode != null) {
            if (aNode.val != bNode.val) {
                return false;
            }
            aNode = aNode.next;
            bNode = bNode.next;
        }
        return true;
    }
    
    private ListNode revert(ListNode head) {
        ListNode pre = null, nxt = null;
        while(head != null) {
            nxt = head.next;
            head.next = pre;
            pre = head;
            head = nxt;
        }
        return pre;
    }
}

[LC] 234. Palindrome Linked List

标签:head   tno   nod   list   bool   output   rom   link   NPU   

原文地址:https://www.cnblogs.com/xuanlu/p/12123663.html

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