题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
//将节点添加到栈里
ListNode tmp=head;
Stack<Integer> stack = new Stack<>();
while (tmp != null) {
stack.push(tmp.val);
tmp = tmp.next;
}
//对比链表每个节点与栈中取出的节点
while(head!=null&&!stack.isEmpty()){
Integer tmpNode=stack.pop();
//不一样就不是回文链表
if(head.val!=tmpNode){
return false;
}
head=head.next;
}
return true;
}
}
查看13道真题和解析
字节跳动公司福利 1297人发布