Problem:
Given a singly linked list, determine if it is a palindrome.
Explanation:
判断链表是否回文。
My Thinking:
使用快慢指针找到链表中点,将慢指针的结点存入栈,注意需要判断奇数还是偶数,随后慢指针继续移动,并与栈中元素判断相等。
My Solution:
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast=head,slow=head;
Stack<ListNode> nodestack=new Stack<>();
if(head==null || head.next==null)
return true;
nodestack.push(slow);
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast!=null)//如果是奇数
nodestack.push(slow);
}
while(slow!=null){
if(nodestack.pop().val!=slow.val)
return false;
slow=slow.next;
}
return true;
}
}
Optimum Thinking:
不使用栈,找到中点后,对后半部分进行逆转。
Optimum Solution:
public boolean isPalindrome(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) { // odd nodes: let right half smaller
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while (slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}