-
题目描述:
请判断一个链表是否为回文链表。 -
输入示例:
- 示例 1:
输入: 1->2
输出: false
- 示例 2:
输入: 1->2->2->1
输出: true
- 解题思路:
- 先找到中间节点
- 然后逆置后半部分节点
- head节点从前开始往中间走,slow节点从后开始往中间走,判断首尾节点的数据是否相等
- 解题代码:
public boolean isPalindrome(ListNode head) {
//为空或者只有一个节点
if(head == null || head.next == null) {
return true;
}
//1.先找到中间节点
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//2.逆置后半部分单链表
ListNode cur = slow.next;
while(cur != null) {
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
//3.head节点从前开始往中间走,slow节点从后开始往中间走
while(slow != head) {
if(slow.val != head.val) {
return false;
}
if(head.next == slow) {//如果是偶数个节点
return true;
}
slow = slow.next;
head = head.next;
}
return true;
}
- 执行结果: