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


    题目标签:Linked List

      题目给了我们一个 linked list,让我们判断它是不是回文。

      这里可以利用 #206 Reverse Linked List 把右边一半的链表 倒转,然后从左右两头开始比较链表是否是回文。

      这样的话,首先要找到链表的中间点,然后开始倒转右半边链表。

      可以利用slow fast pointers 来找到中间点,当fast 走完的时候,slow 正好在中间。

    Java Solution:

    Runtime beats 39.01% 

    完成日期:06/11/2017

    关键词:singly-linked list

    关键点:利用slow fast 指针来找到中间点

     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 class Solution 
    10 {
    11     public boolean isPalindrome(ListNode head) 
    12     {
    13         ListNode slow = head;
    14         ListNode fast = head;
    15         ListNode tail;
    16         
    17         // find the middle
    18         while(fast != null && fast.next != null)
    19         {
    20             slow = slow.next;
    21             fast = fast.next.next;
    22         }
    23         
    24         if(fast != null) // odd length
    25             slow = slow.next; // move middle to right half
    26         
    27         // reverse right half
    28         tail = reverse(slow);
    29         
    30         // compare head and tail
    31         while(tail != null)
    32         {
    33             if(head.val != tail.val)
    34                 return false;
    35             
    36             head = head.next;
    37             tail = tail.next;
    38         }
    39         
    40         return true;
    41     }
    42     
    43     private ListNode reverse(ListNode cursor)
    44     {
    45         ListNode pre = null;
    46         ListNode next;
    47         
    48         while(cursor != null)
    49         {
    50             next = cursor.next;
    51             cursor.next = pre;
    52             pre = cursor;
    53             cursor = next;
    54         }
    55         
    56         return pre; // tail node
    57     }
    58 }

    参考资料:https://discuss.leetcode.com/topic/33376/java-easy-to-understand

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    内存-程序运行的空间
    数据在内存中是这样存储的(二进制形式存储)
    从编写源代码到程序在内存中运行的全过程解析
    QT开发工具
    Linux中Too many open files 问题分析和解决
    TCP端口状态说明ESTABLISHED、TIME_WAIT
    HttpClient当HTTP连接的时候出现大量CLOSE_WAIT连接
    缓存穿透、击穿、雪崩
    Http长连接和Keep-Alive以及Tcp的Keepalive
    防止表单重复提交
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7953766.html
Copyright © 2011-2022 走看看