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;
            }
        }
    }
  • 相关阅读:
    找工作总结
    java设计模式2-观察者模式
    java设计模式1-策略模式
    Hadoop 集群常见错误
    hadoop的conf配置详解
    HDFS的数据导入到HIVE中
    hadoop集群搭建(完全分布式)
    FastDFS的学习
    FastDFS文档整理与研究
    把windows上文件上传到linux系统
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5864643.html
Copyright © 2011-2022 走看看