把链表中所有元素存储到栈中,也就实现了将链表中的元素逆序存放到栈中。然后再将栈中元素一个一个出栈并和链表比对,将链表一个一个往下指
时空间复杂度:O(n)
public static boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
Stack<Integer> stack = new Stack<Integer> ();
ListNode temp = head;
while (temp != null){
stack.push(temp.val);
temp = temp.next;
}
while (head != null){
if(stack.pop() != head.val){
return false;
}
head = head.next;
}
return true;
}
原文:https://www.cnblogs.com/swifthao/p/13081981.html