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?

    链接: http://leetcode.com/problems/palindrome-linked-list/

    2/28/2017

    参考别人的答案,因为一开始不知道可不可以改变list的结构。

     1 public class Solution {
     2     public boolean isPalindrome(ListNode head) {
     3         if (head == null || head.next == null) return true;
     4         ListNode mid = findMidNode(head);
     5         ListNode ret = reverseList(mid);
     6 
     7         while(ret != null) {
     8             if (head.val != ret.val) return false;
     9             head = head.next;
    10             ret = ret.next;
    11         }
    12         return true;
    13     }
    14     private ListNode findMidNode(ListNode head) {
    15         ListNode slow = head;
    16         ListNode fast = head;
    17 
    18         while (fast != null) {
    19             fast = fast.next;
    20             if (fast != null) {
    21                 fast = fast.next;
    22                 slow = slow.next;
    23             }
    24         }
    25         return slow;
    26     }
    27     private ListNode reverseList(ListNode head) {
    28         ListNode dummy = new ListNode(0);
    29         ListNode tmp;
    30         while (head != null) {
    31             tmp = head.next;
    32             head.next = dummy.next;
    33             dummy.next = head;
    34             head = tmp;
    35         }
    36         return dummy.next;
    37     }
    38 }
  • 相关阅读:
    Java 正则表达式
    【 D3.js 进阶系列 — 4.0 】 绘制箭头
    d3.js path路径
    java equals 与 hashCode
    ubuntu14 简单安装ffmpeg
    mysql 导入
    Session的生命周期
    Mysql 乱码配置
    51nod1416(dfs)
    51nod1402(贪心)
  • 原文地址:https://www.cnblogs.com/panini/p/6482291.html
Copyright © 2011-2022 走看看