(https://leetcode-cn.com/problems/aMhZSa/))
public class 剑指Offer_II_027_回文链表 {
public boolean isPalindrome(ListNode head) {
if (head==null) return false;
Stack<ListNode> stack = new Stack<ListNode>();
ListNode node = head;
while (node!=null) {
stack.push(node);
node = node.next;
}
int size = stack.size();
node = stack.pop();
for (int i = 0; i < size >> 1; i++) {
if (!(node.val == head.val)) return false;
node = stack.pop();
head = head.next;
}
return true;
}
}
利用了栈的先进后出特性,如果是回文链表,入栈时正序 的元素和出栈时倒序的元素应该是一样的。