/** * 基于栈判断是否为回文 * 1.使用栈: 所有节点依次入栈,弹出一个与原链表或字符比对有一个不对,不是回文 * 2.使用栈: 利用快慢指针找到链表中点,以slow下一个开始压入栈中,弹出比对,栈为空停止 * isPalindrome2()方法使用了快慢指针,我定义的是 * slow = head.next(); * fast = head.next.next(); * 其实可以改进为 * slow = head; * fast = head; * 可以少一次if判断 */
//遍历链表全部放入栈中,弹出比对
public static boolean isPalindrome1(Node head){
if(head == null){
return false;
}
Stack<Node> stack = new Stack<>();
Node curr = head;
while (curr != null){
stack.push(curr);
curr = curr.next;
}
while (head != null){
if(stack.pop().val != head.val){
return false;
}
head = head.next;
}
return true;
}
/*
0 0 0 0 0
1 1
基于栈结构,减少一半空间
*/
public static boolean isPalindrome2(Node head){
if(head == null){
return false;
}
if(head.next == null){
return true;
}
if(head.next.next == null && head.val != head.next.val){
return false;
}
if(head.next.next != null){
Node slow = head.next;
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
Stack<Node> stack = new Stack<>();
while (slow.next != null){
stack.push(slow.next);
slow = slow.next;
}
Node curr = head;
while (!stack.empty()){
if(stack.pop().val != curr.val){
return false;
}
curr = curr.next;
}
}
return true;
}
左神算法学习