回文链表和链表reverse()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28350997/article/details/83278074

链接
判断一个链表是否是回文字符串?

  • 快慢指针
  • 链表reverse
  • 考虑是偶数链表还是

reverse

以后都构造不包含头节点都结果链表

其实跟我以前都思路是一样的想法,同样是采用头插入法和分开两个链表的做法情况

public void reverse(ListNode head){
     ListNode pre =null;
     while(head!=null){
     ListNode next =head.next;
     head.next =pre;
     pre =head;
     head =next;
}
return pre;
}

如何判断是偶数链表还是单链表的情况下
主要有下面的判断准则

判断是否为空,如果最后fast为空,则为偶数链表,
如果fast不为空,则为奇数链表,这种情况

按照上述做法,找到最后一个

最终的代码结构如下

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public boolean isPalindrome(ListNode head) {
         if(head==null|| head.next==null) {return true;}
         ListNode slow = head,fast=head;
        
         slow = middle(head);
         slow = reverse(slow);
      
        
        while(fast!=null && slow!=null){
             if(fast.val!=slow.val){
                 return false;
             }
             fast = fast.next;
             slow = slow.next;
         }
         return true;
    }
        
     private ListNode middle(ListNode head){
         ListNode slow = head;
         ListNode fast = head;

         while(fast!=null&& fast.next!=null){
             fast =fast.next.next;
             slow = slow.next;
         }

         if(count(head)%2==1) {slow = slow.next;}

         return slow;
    }
        private ListNode reverse(ListNode head){
       //不构造一个头节点,直接返回即可

        ListNode pre =null;

        while(head!=null){
            ListNode next= head.next;
            head.next = pre;
            pre = head;
            head  = next;
        }
        return pre;
    }
    
     private int count(ListNode head){
        int count =0;
        while(head!=null)
        {
            ++count;
            head = head.next;
        }
        return count;
    }

    
   

    
}

猜你喜欢

转载自blog.csdn.net/qq_28350997/article/details/83278074