欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > leetcode234.回文链表

leetcode234.回文链表

2025/3/31 16:21:00 来源:https://blog.csdn.net/weixin_74175349/article/details/146569339  浏览:    关键词:leetcode234.回文链表

 先利用快慢指针将链表一分为2,后半部分链表进行反转,然后两个链表一一比对就可以判断是否回文了

/*** 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) {//用快慢指针将链表一分为二ListNode slow=head;ListNode fast=head.next;while (fast != null && fast.next != null) {slow=slow.next;fast=fast.next.next;}//反转后半部分链表ListNode secondPartNode = this.reverse(slow.next);//前后部分比对看是否是回文链表ListNode firstPartNode=head;while (firstPartNode != null && secondPartNode != null) {if (firstPartNode.val != secondPartNode.val) {return false;}firstPartNode=firstPartNode.next;secondPartNode=secondPartNode.next;}return true;}private ListNode reverse(ListNode head){if (head == null) {return head;}ListNode pre=null;while (head != null) {ListNode temp=head.next;head.next=pre;pre=head;head=temp;}return pre;}
}

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词