zoukankan      html  css  js  c++  java
  • 234. Palindrome Linked List

    Given a singly linked list, determine if it is a palindrome.

    Example 1:

    Input: 1->2
    Output: false

    Example 2:

    Input: 1->2->2->1
    Output: true

    Follow up:
    Could you do it in O(n) time and O(1) space?


    (1)定义快慢指针得到链表的中点 (2)将后半部分逆序 (3)从头节点和中点开始比较是否相同

     public boolean isPalindrome(ListNode head) {
            if (head == null || head.next == null) {
                return true;
            }
            ListNode slow=head;
            ListNode fast=head;
            while (fast.next!=null&&fast.next.next!=null){
                slow=slow.next;
                fast=fast.next.next;
            }
            reverseList(slow.next);
            slow=head;
            while (fast!=null){
                if (fast.val!=slow.val)
                    return false;
                fast=fast.next;
                slow=slow.next;
            }
            return true;
        }
    
        public ListNode reverseList(ListNode head) {
            if (head.next == null)
                return head;
            ListNode node = reverseList(head.next);
            head.next.next=head;
            head.next=null;
            return node;
        }
    

      

    加油啦!加油鸭,冲鸭!!!
  • 相关阅读:
    Windows Phone 7 电话本相关的操作
    Windows CE 下判断 URL 地址是否有效
    cigarettes
    开灯问题
    日期计算
    小学生算术
    另一种阶乘问题
    鸡兔同笼
    笨小熊
    6174问题
  • 原文地址:https://www.cnblogs.com/clarencezzh/p/10957034.html
Copyright © 2011-2022 走看看