题目描述:
请判断一个链表是否为回文链表。
示例:
输入: 1->2->2->1
输出: true
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode fast = head, slow = head;
ListNode pre = head, prepre = null;
while(fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
pre.next = prepre;
prepre = pre;
}
if(fast != null) slow = slow.next;
while(pre != null && slow != null) {
if(pre.val != slow.val) return false;
pre = pre.next;
slow = slow.next;
}
return true;
}
}
网友评论