题目描述
判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路及解答
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
* 思路:利用链表反转法
* 将链表后半段原地翻转,再将前半段和后半段依次比较
* 所以,首先要找到中间结点,这里使用快慢指针法
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//如果链表为null或者只有一个元素那么肯定是回文链表
if(head == null || head.next == null)
return true;
//寻找中点,最后slow的位置正好是中点
ListNode slow = head;
ListNode fast = head;
ListNode tail;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//如果fast指向的是null,说明链表的长度是偶数;如果fast指向不为null,说明链表的长度为奇数
//如果链表长度为奇数,slow指向的下一个结点是需要开始反转的结点;如果链表的长度为偶数,则从slow指向的位置开始反转链表
if(fast != null){
slow = slow.next;
}
tail = reverseList(slow);
//比较是否相同
while(tail != null){
if(head.val != tail.val){
return false;
}
head = head.next;
tail = tail.next;
}
return true;
}
//将链表进行反转
public ListNode reverseList(ListNode head){
if(head == null)
return null;
ListNode p1 = head;
ListNode p2 = head.next;
p1.next = null;
while(p2 != null){
ListNode temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
}