首页 > 其他 > 详细

[LC] 234. Palindrome Linked List

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!