• LC.234.Palindrome Linked List


    https://leetcode.com/problems/palindrome-linked-list/description/
    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?
    time O(n) space:O(1)

    (1) 先找中点
    (2) 再reverse后半段
    (3) 不用管两个子linked list的长度是否相等,从各个子链表的头开始一个一个比较。值不相等就返回false,相等就继续移动。

    当取中点时,一定要 fast.next.next != null 

     1 public boolean isPalindrome(ListNode head) {
     2         if (head == null) return true ;
     3         ListNode fast = head , slow = head ;
     4         ListNode mid = null ;
     5         //step 1: find the middle node: when fast reaches the end, slow reaches the mid
     6         //note: middle node has to be fast.next != null && fast.next.next != null
     7         while (fast != null && fast.next != null && fast.next.next != null){
     8             fast = fast.next.next ;
     9             slow = slow.next ;
    10         }
    11         //ab' b''a   mid == b'
    12         mid = slow;
    13         // secHalfHead == b''
    14         ListNode secHalfHead = mid.next ;
    15         //step 2: reverse the 2nd half
    16         ListNode lastHead = reverse(secHalfHead) ;
    17         //step 3: compare the 1st half with the 2nd half, if not the same return false
    18         while (head != null && lastHead != null){
    19             if (head.val != lastHead.val) {
    20                 return false ;
    21             }
    22             head = head.next ;
    23             lastHead = lastHead.next ;
    24         }
    25         return true ;
    26     }
    27 
    28     /*1->2->3->4   to 1<-2<-3<-4
    29     *                          p c
    30     * */
    31     private ListNode reverse(ListNode head){
    32         ListNode pre = null ;
    33         ListNode curr = head ;
    34         while (curr!= null){
    35             ListNode temp = curr.next ;
    36             curr.next = pre ;
    37             pre = curr ;
    38             curr = temp;
    39         }
    40         return pre ;
    41     }

     

  • 相关阅读:
    [bbk5102] 第38集 第四章 Flashback Database 02
    index
    [bbk5110] 第41集 第四章 Flashback Database 05
    支持向量机SVM基本问题
    凸优化小结
    博客基本操作
    感知机vs支持向量机
    PAYPAL商户集成指南-IPN&PDT变量列表
    一个IBM人的离职泪:伟大公司,SB老板,苦逼员工 (zz.IS2120.BG57IV3)
    Google Reader 7.1停止服务
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8464293.html
Copyright © 2020-2023  润新知