判断一个链表是否为回文链表。
该题目来自力扣题库
示例
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路
使用栈结构,把当前链表全部压入堆栈。之后再按顺序比较链表节点以及出栈节点是否相同
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null){
return true;
}
Stack<ListNode> stack=new Stack<ListNode>();
ListNode cur=head;
while(cur!=null){
stack.push(cur);
cur=cur.next;
}
cur=head;
while(stack.size()>0){
ListNode prev=stack.pop();
if(cur.val!=prev.val){
return false;
}
cur=cur.next;
}
return true;
}
}