LeetCode链接:力扣
题目:
给定一个链表的 头节点 head
,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
示例:
输入: head = [1,2,3,3,2,1]
输出: true
代码:(快慢指针,时间复杂度O(n),空间复杂度O(1))
/**
* 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) {
if(head == null){
return true;
}
//快慢指针,找到中间节点
ListNode firstHalfEnd = endOfFirstHalf(head);
//反转链表
ListNode secondHalfStar = reverseList(firstHalfEnd.next);
ListNode p1 = head;
ListNode p2 = secondHalfStar;
boolean result = true;
while(result && p2 != null){
if(p1.val != p2.val){
result = false;
}
p1 = p1.next;
p2 = p2.next;
}
firstHalfEnd.next = reverseList(secondHalfStar);
return result;
}
private ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode curr = head;
while(curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
private ListNode endOfFirstHalf(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
还可以用数组来装链表的值,用数组操作来判断
或者用递归做
详情:力扣