领扣算法:234 回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
输入参数: public boolean isPalindrome(ListNode head)
解决步骤:
1.借助一个栈来实现,遍历链表将每个元素入栈
2.逐一比较链表中的每一个元素和每次出栈的栈顶元素,如果有不相等的元素,返回false,如果没有,返回true
代码:
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
Stack<ListNode> temp = new Stack<>();
ListNode cur = head;
while(cur!=null){
temp.push(cur);
cur = cur.next;
}
while(head!=null){
if(head.val != temp.pop().val){
return false;
}
head = head.next;
}
return true;
}
运行截图: