题目描述
请判断一个链表是否为回文链表。
解题思路
1、代码1对于链表来,不能直接用双指针同时遍历。如果我们开创一个额外空间,创建一个辅助列表,将链表拷贝到列表中,利用列表的索引来比较。
2、代码2进阶:要求空间复杂度为O(1)
利用快慢指针,同时结合反转。现在简单理解,快指针指到链表的末端,慢指针指到链表的中间,再将后半部分的链表反转。代码没有完全理解,后面再理解
**思路:**将链表切成两段,把后半段反转,然后比较这两段的值是否相等
代码1
/**
* 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;
ArrayList<Integer> list = new ArrayList<>();
ListNode cur = head;
while(cur != null){
list.add(cur.val);
cur = cur.next;
}
int lo = 0;
int hi = list.size() - 1;
while(lo <= hi){
if(!list.get(lo).equals(list.get(hi))){
return false;
}
lo++;
hi--;
}
return 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;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
return isEqual(head, reverse(fast));
}
//把链表反转
private ListNode reverse(ListNode head){
ListNode pre = null;
while(head != null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
//比较两个链表的值是否相等
private boolean isEqual(ListNode l1, ListNode l2){
while(l1 != null && l2 != null){
if(l1.val != l2.val) return false;
l1 = l1.next;
l2 = l2.next;
}
return true;
}
}
参考:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-yuan-di-jian-cha-bu-yong-fan-zhu/
https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand