zoukankan      html  css  js  c++  java
  • 【LeetCode】234 Palindrome Linked List

    Palindrome Linked List
    Total Accepted: 1116 Total Submissions: 4295 My Submissions Question Solution 
    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?


    Hide Tags Linked List Two Pointers
    【解题思路】
    1、遍历链表,快慢指针,找到链表后半部分。
    2、反转链表,能够參考Reverse Linked List
    3、然后比較前半部分和后半部分的val值。


    Java AC

    /**
     * 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;
            }
            ListNode slow = head;
            ListNode fast = slow.next;
            while (fast != null && fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode p = slow.next;
            ListNode q;
            ListNode end = null;
            while (p != null) {
                q = p.next;
                p.next = end;
                end = p;
                p = q;
            }
            while (head != null && end != null) {
                if (head.val != end.val) {
                    return false;
                }
                head = head.next;
                end = end.next;
            }
            return true;
        }
    }


  • 相关阅读:
    php或JS中输出判断项
    拿大神的博客来记一下
    2017.6.8 项目进展
    2017.6.8
    2017.5.18
    2017.5.17
    2017.5.16
    如何实现从php传数据到js
    项目笔记
    tp框架之Model类与命名空间
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/8794931.html
Copyright © 2011-2022 走看看