首页 > 代码库 > LeetCode 234 Palindrome Linked List

LeetCode 234 Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

 

思路:

回文结构从后向前遍历与从前向后遍历的结果是相同的,可以利用一个栈的结构,将出栈元素与正向移动的指针指向元素比较,即可判断。

 

解法:

 1 /* 2     public class ListNode 3     { 4         int val; 5         ListNode next; 6  7         ListNode(int x) 8         { val = x; } 9     }10 */11 12 import java.util.Stack;13 14 public class Solution15 {16     public boolean isPalindrome(ListNode head)17     {18         if(head == null || head.next == null)19             return true;20 21         Stack<ListNode> stack = new Stack<>();22         ListNode flag = head;23 24         while(flag != null)25         {26             stack.push(flag);27             flag = flag.next;28         }29 30         while(head != null)31         {32             if(head.val != stack.pop().val)33                 return false;34             head = head.next;35         }36 37         return true;38     }39 }

 

LeetCode 234 Palindrome Linked List