zoukankan      html  css  js  c++  java
  • *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?

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     /**
    11      * @param head a ListNode
    12      * @return a boolean
    13      */
    14     public boolean isPalindrome(ListNode head) {
    15         if (head == null) {
    16             return true;
    17         }
    18         
    19         ListNode middle = findMiddle(head);
    20         middle.next = reverse(middle.next);
    21         
    22         ListNode p1 = head, p2 = middle.next;
    23         while (p1 != null && p2 != null && p1.val == p2.val) {
    24             p1 = p1.next;
    25             p2 = p2.next;
    26         }
    27         
    28         return p2 == null;
    29     }
    30     
    31     private ListNode findMiddle(ListNode head) {
    32         if (head == null) {
    33             return null;
    34         }
    35         ListNode slow = head, fast = head;
    36         while (fast!=null&& fast.next != null && fast.next.next != null) {
    37             slow = slow.next;
    38             fast = fast.next.next;
    39         }
    40         
    41         return slow;
    42     }
    43     
    44     private ListNode reverse(ListNode head) {
    45         ListNode prev = null;
    46         ListNode current = head;
    47         
    48         while (current != null) {
    49             ListNode temp = current.next;
    50             current.next = prev;
    51             prev = current;
    52             current = temp;
    53         }
    54         
    55         return prev;
    56     }
    57 }

    reference: https://www.youtube.com/watch?v=sYcOK51hl-A

     
  • 相关阅读:
    基于雪花算法的单机版
    Spring cloud gateway自定义filter以及负载均衡
    logback转义符与MDC
    录音地址文件保存
    maven加载本地jar
    ES Log4J配置信息
    java线程池
    openstreetmap的数据下载
    php更新版本后(路径更改后)要做的调整
    重启IIS
  • 原文地址:https://www.cnblogs.com/hygeia/p/4899812.html
Copyright © 2011-2022 走看看