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;
            }
        }
    }
  • 相关阅读:
    学习视频资料下载论坛
    2007年12月英语四级预测作文大全1
    主板报警声音大全
    2007年12月英语四级预测作文大全1
    主板报警声音大全
    LOGO在线制作
    武汉之行收获
    武汉之行
    心灵小栈: 镌刻在地下500米的母爱
    一道终身受益的测试题
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5864643.html
Copyright © 2011-2022 走看看