zoukankan      html  css  js  c++  java
  • 234. 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、从中点开始反转链表,判断是否相等。

     1 class Solution {
     2     public boolean isPalindrome(ListNode head) {
     3         ListNode faster= head ,slower= head;
     4         while(faster!=null && faster.next!=null){
     5             faster = faster.next.next;
     6             slower = slower.next;
     7         }
     8         if(faster!=null)
     9             //奇数
    10             slower=slower.next;
    11         ListNode newhead = Reverse(slower);
    12         while(newhead!=null){
    13             if(head.val!=newhead.val){
    14                 return false;
    15             }
    16             head = head.next;
    17             newhead = newhead.next;
    18         }
    19             return true;
    20 
    21     }
    22 
    23     public ListNode  Reverse(ListNode head) {
    24         if(head == null ||head.next == null) return head;
    25         ListNode pre = head;
    26         head = head.next;
    27         pre.next = null;
    28         while(head != null){
    29             ListNode next = head.next;
    30             head.next = pre;
    31             pre = head;
    32             head = next;
    33         }
    34         return pre;
    35     }
    36 
    37 }
  • 相关阅读:
    spring-boot4
    spring-boot3代码
    spring-boot3
    spring-boot2代码
    spring-boot2
    Java Socket编程
    eclipse项目中.classpath文件详解
    spring-boot1
    ASCII 在线转换器
    如何在Android开发中让你的代码更有效率
  • 原文地址:https://www.cnblogs.com/zle1992/p/7583276.html
Copyright © 2011-2022 走看看