234-回文链表

时间:2019-05-15
本文章向大家介绍234-回文链表,主要包括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;
   }

原文地址:https://www.cnblogs.com/dloading/p/10872074.html