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

    思想:转置后半段链表节点,然后比较前半段和后半段节点的值是否相等。

    代码如下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null || head.next==null) return true;
            
            int len=0,tmp=0;
            ListNode p=head,q=head,r=head,s=head;
            int m1=0,m2=0;
            int n1=0,n2=0;
            while(p!=null){
                len++;
                p=p.next;
            }
            if(len==2){
                if(head.val==head.next.val)
                   return true;
                else
                   return false;
            }
            p=head;
            if(len%2==1){
               m1=0;
               m2=len/2+1;
               n1=m2-2;
               n2=len-1;
                
            }else{
                m1=0;
                m2=len/2;
                n1=m2-1;
                n2=len-1; 
                
            }
            while(p!=null && tmp!=m2){
                    p=p.next;   
                    tmp++;
                  }  //p到达转置数组的头部
              q=p;
            if(p.next!=null){
                 q=p;
                 p=p.next;
                 q.next=null;
                 
                 while(p!=null){
                     r=p.next;
                     p.next=q;
                     q=p;
                     p=r;
                 }//while 循环后,q指后半段头
              }  
                while(q!=null &&s.val==q.val){
                    q=q.next;s=s.next;
                }
                if(q==null)
                   return true;
                else
                   return false;
               
        }
    }
    

      运行结果:

          

  • 相关阅读:
    DS博客作业05--查找
    DS博客作业04--图
    数据结构-栈,队列
    我の第六篇博客
    我の第五篇博客
    我の第四篇博客
    我の第三篇博客
    我の第二篇博客
    Java 购物车大作业01
    有理数类的设计
  • 原文地址:https://www.cnblogs.com/mlz-2019/p/4692791.html
Copyright © 2011-2022 走看看