234. 回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
答案
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
int size = 0;
ListNode temp = head;
while (temp != null) {
temp = temp.next;
size++;
}
int k = size / 2;
temp = head;
while (size-- > k) {
temp = temp.next;
}
temp = reverseList(temp);
while (temp != null) {
if (temp.val != head.val) {
return false;
}
temp = temp.next;
head = head.next;
}
return true;
}
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode res = null, t;
while(head != null) {
t = head.next;
head.next = res;
res = head;
head = t;
}
return res;
}
}