题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
- 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法
思路一: 先把链表的值都存进list中,然后再判断list是否存在回文性质。
/**
* 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 {
/**
思路一:先把链表的值都存进list中,然后再判断list是否存在回文性质
*/
public boolean isPalindrome(ListNode head) {
if(head == null){
return true;
}
List<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
int left = 0 , right = list.size()-1;
while(left < right){
if(!list.get(left).equals(list.get(right))){
return false;
}
left++;
right--;
}
return true;
}
}
思路二: 快慢指针。
快指针每次走两个格,慢指针每次走一个格,当快指针到达结尾的时候,慢指针刚好走到中间,然后反转慢指针后面的所有链表,然后再与链表的前半部分进行比较。
/**
* 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 {
/**
思路二:快慢指针。
要实现 O(n) 的时间复杂度和 O(1) 的空间复杂度,需要翻转后半部分
*/
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
ListNode fast = head , slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
slow = reverse(slow.next);
while(slow != null){
if(head.val != slow.val){
return false;
}
head = head.next;
slow = slow.next;
}
return true;
}
/**
反转链表
*/
private ListNode reverse(ListNode head){
// 递归到最后一个节点,返回新的头结点
if(head.next == null){
return head;
}
ListNode newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
总结
本篇文章讲解了算法题目的思路和解法,代码和笔记由于纯手打,难免会有纰漏,如果发现错误的地方,请第一时间告诉我,这将是我进步的一个很重要的环节。以后会定期更新算法题目以及各种开发知识点,如果您觉得写得不错,不妨点个关注,谢谢。