题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 1 2 2 1 --> 1 2 2 1 * * * @param head ListNode类 the head * @return bool布尔型 */ public boolean isPail (ListNode head) { if (head == null || head.next == null) { return true; } // 先把所有的节点放入到Stack中 Stack<ListNode> stack = new Stack<>(); ListNode tempNode = head; stack.push(tempNode); while (tempNode.next != null) { tempNode = tempNode.next; stack.push(tempNode); } tempNode = head; while(!stack.isEmpty()) { if(stack.pop().val != tempNode.val) { return false; } tempNode = tempNode.next; } return true; } }