知识点
链表,队列
解题思路
靠单链表这个数据结构我们很难从尾到头遍历,单可以使用双端队列。
双端队列可以从头和尾放入取出。
把链表节点全部放到队列中,再从头和从尾取出节点判断是否相等,不相等则直接返回false。
Java题解
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return bool布尔型
*/
public boolean isPalindrome (ListNode head) {
// write code here
Deque<ListNode> deque = new LinkedList<>();
while(head != null) {
deque.addFirst(head);
head = head.next;
}
while(deque.size() > 1){
if(deque.pollFirst().val != deque.pollLast().val){
return false;
}
}
return true;
}
}



京公网安备 11010502036488号