1. 题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
2. 代码实现
思路:先找到链表的中点(利用快慢指针),再把后半部分逆序,再进行对比。
/**
* 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;
//利用快慢两个指针找到中点,即slow最终所指结点
ListNode slow = head, fast = head;
while(fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//后半部分逆序
ListNode temp, pre = null;
while(slow != null) {
temp = slow.next;
slow.next = pre;
pre = slow;
slow = temp;
}
//前后两个部分比较
while(head != null && pre != null) {
if(head.val != pre.val)
return false;
head = head.next;
pre = pre.next;
}
return true;
}
}