class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null){//有0个或1个节点
return true;
}
ListNode right=head.next;
ListNode cur=head;
//靠cur确定右半区起始点位置(right)
while(cur.next!=null&&cur.next.next!=null){
right=right.next;
cur=cur.next.next;
}
//把右半区压入栈
Stack<ListNode> stack=new Stack<ListNode>();
while(right!=null){
stack.push(right);
right=right.next;
}
//比较左半区和栈中弹出的值,如12321左半区12、右半区21压入栈后弹出顺序为12
while(!stack.isEmpty()){
if(head.val!=stack.pop().val){
return false;
}
head=head.next;
}
return true;
}
}
leetcode:17.回文链表 简单
最新推荐文章于 2024-09-08 20:02:08 发布