zoukankan      html  css  js  c++  java
  • 234-回文链表

    请判断一个链表是否为回文链表。
    
    示例 1:
    
    输入: 1->2
    输出: false
    示例 2:
    
    输入: 1->2->2->1
    输出: true
    进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
    
    解法1:栈
    
     public boolean isPalindrome(ListNode head) {
            if (head==null)
                return true;
            ListNode a=head;
            Stack stack=new Stack();
            while (a!=null){
                stack.push(a);
                a=a.next;
            }
            while (head!=null){
                ListNode node= (ListNode) stack.pop();
                if (node.val!=head.val){
                    return false;
                }else {
                    head=head.next;
                }
            }
            return true;
        }
    
    
    解法2:快慢指针
    
      public boolean isPalindrome(ListNode head) {
           if (head==null || head.next==null)
               return true;
           ListNode fast=head;
           ListNode slow=head;
           while (fast.next!=null&&fast.next.next!=null){
               fast=fast.next.next;
               slow=slow.next;
           }
           ListNode lastHalf=reverseListNode(slow.next);
           while (lastHalf!=null){
               if (head.val!=lastHalf.val){
                   return false;
               }
               head=head.next;
               lastHalf=lastHalf.next;
           }
           return true;
       }
       public ListNode reverseListNode(ListNode slow){
           ListNode head=slow;
           ListNode a=null;
           while (slow!=null){
               ListNode b=slow.next;
               head.next=a;
               a=head;
               head=b;
               slow=b;
           }
           return a;
       }
  • 相关阅读:
    jQuery获取Select选择的Text和 Value(转)
    android学习---EditText
    android学习---Activity
    android学习---LinearLayout
    android学习---布局Layout
    android颜色码制表
    java面试题二
    java面试题一
    基本排序算法java实现
    Integer与int的区别
  • 原文地址:https://www.cnblogs.com/dloading/p/10872074.html
Copyright © 2011-2022 走看看