LeetCode-234-回文链表

思路
1.数组法
把链表中的数据复制到数组中,然后使用两个指针从首尾进行比较
时间复杂度O(n),空间复杂度O(n)
2.翻转链表法
可以把后半部分的链表进行翻转,然后使用两个指针从首部和中间开始遍历进行比较
时间复杂度O(n),空间复杂度O(1)
代码
//数组法
public boolean isPalindrome(ListNode head) {
List<Integer> list=new ArrayList<>();
ListNode p=head;
while(p!=null){
list.add(p.val);
p=p.next;
}
int l=0,r=list.size()-1;
while(l<r){
if(list.get(l)!=list.get(r))return false;
l++;
r--;
}
return true;
}
//翻转链表法
public boolean isPalindrome(ListNode head) {
if(head==null)return true;
ListNode mid=findMiddle(head);
ListNode n1=head;
ListNode n2=reverseList(mid.next);
while(n2!=null){
if(n1.val!=n2.val){
reverseList(mid.next);
return false;
}
n1=n1.next;
n2=n2.next;
}
return true;
}
public ListNode reverseList(ListNode head){
ListNode cur=null;
ListNode pre=head;
while(pre!=null){
ListNode t=pre.next;
pre.next=cur;
cur=pre;
pre=t;
}
return cur;
}
public ListNode findMiddle(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
本文介绍了LeetCode题目234如何通过数组法和翻转链表法判断链表是否为回文,两种方法的时间复杂度均为O(n),空间复杂度分别为O(n)和O(1)。详细展示了代码实现和关键步骤。
234

被折叠的 条评论
为什么被折叠?



