-
-
Save jason51122/ca90d321da5a21c80ed1 to your computer and use it in GitHub Desktop.
2.7 Implement a function to check if a linked list is a palindrome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean linkedListPalindrome(ListNode head) { | |
if (head == null || head.next == null) { | |
return true; | |
} | |
ListNode slow = head; | |
ListNode fast = head; | |
Stack<Integer> s = new Stack<Integer>(); | |
s.push(slow.val); | |
while (fast.next != null && fast.next.next != null) { | |
slow = slow.next; | |
fast = fast.next.next; | |
s.push(slow.val); | |
} | |
// The number of nodes is odd when fast is the last. | |
if (fast.next == null) { | |
s.pop(); | |
} | |
slow = slow.next; | |
while (slow != null) { | |
if (s.pop() != slow.val) { | |
return false; | |
} | |
slow = slow.next; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment