回文链表
解法一:链表遍历
import java.util.Stack;
public class LeetCode_234 {
public static boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode cur = head;
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
Stack<Integer> temp = new Stack<>();
ListNode newCur = head;
for (int i = 1; i <= count / 2; i++) {
temp.push(newCur.val);
newCur = newCur.next;
}
int start;
if (count % 2 == 0) {
start = count / 2 + 1;
} else {
start = count / 2 + 2;
newCur = newCur.next;
}
for (int i = start; i <= count; i++) {
if (temp.pop() != newCur.val) {
return false;
}
newCur = newCur.next;
}
return true;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(0);
head.next.next = new ListNode(1);
System.out.println(isPalindrome(head));
}
}