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 }
  • 相关阅读:
    XCode 7 运行 cocos2dx 2.2.6问题小节
    SerializeField和Serializable
    convert2utf8withbom
    NGUI制作字体的三种方法
    js json stringify
    nodejs npm 使用淘宝 NPM 镜像
    js url?callback=xxx xxx的介绍
    强引用 弱引用
    关于xml里的encoding
    js 历史
  • 原文地址:https://www.cnblogs.com/zle1992/p/7583276.html
Copyright © 2011-2022 走看看