# 题目

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

示例 1:

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

# 解法一:使用快慢指针

主要思路:

  • 使用快慢指针,快指针走到最后一个结点时,慢指针应该走到链表中间的位置。
  • 翻转慢指针结点后面的链表,与 head 进行比较
public class Solution {
      public boolean isPalindrome(ListNode head) {
        ListNode slow = head,fast = head;
        //fast 先走到 mid 位置
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next == null ? fast.next: fast.next.next;
        }
        // 然后 slow 从 mid 位置开始翻转 
         slow = reverse(slow);
        while(slow.next != null){
            if(head.val != slow.val){
                return false;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }
    private ListNode reverse(ListNode head){
       
        if(head.next == null){
            return head;
        }
        ListNode newHead = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

时间复杂度: O(n)

空间复杂度:O(1)

# 解法二:利用栈的特点

主要思路:

栈是先进先出,遍历链表,存入 stack,然后一个一个弹出来比较,是否一样。

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

时间复杂度: O (n) 遍历了一个链表

空间复杂度: O (n),开辟了一个 stack