zoukankan      html  css  js  c++  java
  • [Algo] 306. Check If Linked List Is Palindrome

    Given a linked list, check whether it is a palindrome.

    Examples:

    Input:   1 -> 2 -> 3 -> 2 -> 1 -> null

    output: true.

    Input:   1 -> 2 -> 3 -> null  

    output: false.

    /**
     * class ListNode {
     *   public int value;
     *   public ListNode next;
     *   public ListNode(int value) {
     *     this.value = value;
     *     next = null;
     *   }
     * }
     */
    public class Solution {
      public boolean isPalindrome(ListNode head) {
        // Write your solution here
        ListNode revNode = reverse(head);
        ListNode cur = head;
        while (cur != null && revNode != null) {
          if (cur.value != revNode.value) {
            return false;
          }
          cur = cur.next;
          revNode = revNode.next;
        }
        return cur == null && revNode == null;
      }
    
      private ListNode reverse(ListNode node) {
        ListNode head = null;
        while (node != null) {
          ListNode newNode = new ListNode(node.value);
          newNode.next = head;
          head = newNode;
          node = node.next;
        }
        return head;
      }
    }
    /**
     * class ListNode {
     *   public int value;
     *   public ListNode next;
     *   public ListNode(int value) {
     *     this.value = value;
     *     next = null;
     *   }
     * }
     */
    public class Solution {
      public boolean isPalindrome(ListNode head) {
        // Write your solution here
        if (head == null || head.next == null) {
          return true;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
          fast = fast.next.next;
          slow = slow.next;
        }
        ListNode mid = slow;
        mid.next = reverse(mid.next);
    
        ListNode revNode = mid.next;
        ListNode cur = head;
        while (cur != null && revNode != null) {
          if (cur.value != revNode.value) {
            return false;
          }
          cur = cur.next;
          revNode = revNode.next;
        }
        return true;
      }
    
      private ListNode reverse(ListNode node) {
        ListNode prev = null;
        while (node != null) {
          ListNode nxt = node.next;
          node.next = prev;
          prev = node;
          node = nxt;
        }
        return prev;
      }
    }
  • 相关阅读:
    define的用法
    MySQL索引使用方法和性能优化
    自己写的一个Js小插件
    .net处理JSON简明教程
    史上最全的ASP.NET MVC路由配置,以后RouteConfig再弄不懂神仙都难救你啦~
    Python面向对象之-反射
    Python内置函数之classmetho staticmethod
    Python内置函数之-property
    python面向对象三大特性-多态
    python面向对象三大特性之封装
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12329863.html
Copyright © 2011-2022 走看看