题解 | 判断一个链表是否为回文结构
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public boolean isPail (ListNode head) {
// write code here
if (head == null || head.next == null) {
return true;
}
Stack<Integer> p = new Stack<>();
ListNode cur = head;
while(cur != null) {
p.push(cur.val);
cur = cur.next;
}
ListNode cur2 = head;
while(!p.isEmpty()) {
int g = p.pop();
int val = cur2.val;
if (g != val) {
return false;
}
cur2 = cur2.next;
}
return true;
}
public ListNode reverseListNode(ListNode reverseNode) {
//O(1)的反转链表
if (reverseNode == null) {
return reverseNode;
}
ListNode current = reverseNode;
ListNode prev = null;
while(current != null) {
ListNode tmp = current.next;
current.next = prev;
prev = current;
current = tmp;
}
return prev;
}
}
思路,反转链表, 然后遍历,如果相等则返回true,但是反转链表在这个ide里会改变原来的值
因此用堆栈先遍历并存储链表的值,然后判断值是否相等即可。


正浩创新EcoFlow公司福利 608人发布