234. 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

示例 1:

输入:head = [1,2,2,1]
输出:true
示例 2:


输入:head = [1,2]
输出:false

解法一:用Stack来实现,先依次进栈,再出栈时依次比较值是否一样

如果是回文,那么进出栈的顺序一样

 public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null){
            return true;
        }
        Stack<Integer> stack=new Stack<>();
        ListNode cur=head;
        while(cur!=null){
            stack.push(cur.val);
            cur=cur.next;
        } 
        while(head!=null){
            if(!stack.pop().equals(head.val)){
                return false;
            }
            head=head.next;
        }
        return true;
  
    }

  

进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

  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;
       }
       ListNode next=slow.next;
       slow.next=null;
       ListNode rNode=reverse(next);
       while(head!=null&&rNode!=null){
           if(head.val!=rNode.val){
               return false;
           }
           head=head.next;
           rNode=rNode.next;
       }

        return true;
  
    }

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

  

 

posted @ 2021-09-03 10:54  sherry001  阅读(59)  评论(0)    收藏  举报