设计一种方式检查一个链表是否为回文链表。
1->2->1
就是一个回文链表。
遍历链表,将其所有元素依次压栈。然后依次出栈与原链表进行比较。
将链表取一半压入栈中,与另一半进行比较。(采用快慢指针法)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode p = head;
while (p != null) {
stack.push(p);
p = p.next;
}
while (!stack.empty()) {
if (stack.pop().val != head.val) {
return false;
}
head = head.next;
}
return true;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
Stack<ListNode> stack = new Stack<ListNode>();
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
stack.push(slow);
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {
slow = slow.next;
}
while (!stack.empty()) {
if (stack.pop().val != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}