题目链接
解题思路
- 首先遍历一次链表,将链表每个节点值存放到栈中
- 然后再次遍历链表,同时从栈中往外
pop
,并对比,如果不同则返回false
AC代码
class Solution {
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 (head.val != stack.pop())
return false;
head = head.next;
}
return true;
}
}