Given a singly linked list, determine if it is a palindrome.
思路:
回文结构从后向前遍历与从前向后遍历的结果是相同的,可以利用一个栈的结构,将出栈元素与正向移动的指针指向元素比较,即可判断。
解法:
/* public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } */ import java.util.Stack; public class Solution { public boolean isPalindrome(ListNode head) { if(head == null || head.next == null) return true; Stack<ListNode> stack = new Stack<>(); ListNode flag = head; while(flag != null) { stack.push(flag); flag = flag.next; } while(head != null) { if(head.val != stack.pop().val) return false; head = head.next; } return true; } }