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 }
  • 相关阅读:
    models F Q查询
    Django models 多对多 操作
    Cookies与session的区别
    Form表单验证
    图片上传
    Django进阶
    sql 单个字段去重查询 distinc 和 group by的效率问题
    Django知识点整理
    Web应用请求和响应 HTTP相关
    Django中的几种重定向方式
  • 原文地址:https://www.cnblogs.com/zle1992/p/7583276.html
Copyright © 2011-2022 走看看