zoukankan      html  css  js  c++  java
  • LeetCode-Palindrome Linked List

    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?

    Analysis:

    1. Use slow+fast pointers to find out the median point.

    2. Reverse the later half of list in-place.

    3. Compare the two half lists.

    4. (if needed), reverse the later half again to get the list back to original.

    Solution:

    /**
     * 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) return true;
            if (head.next==null) return true;
            
            ListNode preHead = new ListNode(0);
            preHead.next = head;
            ListNode p1 = head, p2 = head;
            while (p2.next!=null && p2.next.next!=null){
                p1 = p1.next;
                p2 = p2.next.next;
            }
            
            ListNode preHead2 = p1;
            reverseList(preHead2);
            p1 = preHead.next;
            p2 = preHead2.next;
            
            while (p2!=null){
                if (p1.val!=p2.val){
                    return false;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            return true;
        }
        
        public void reverseList(ListNode preHead){
            ListNode cur = preHead.next;
            while (cur.next!=null){
                ListNode next = cur.next;
                cur.next = next.next;
                next.next = preHead.next;
                preHead.next = next;
            }
        }
    }
  • 相关阅读:
    正则表达式学习1
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
    (转)DBUS基础知识
    WakeLock的使用
    观察者模式
    Notification的使用
    Head First 设计模式之入门
    (转)Android WebView总结
    书架也是一根筋
    PendingIntent分析
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5864643.html
Copyright © 2011-2022 走看看