欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 【Hot100】LeetCode—234. 回文链表

【Hot100】LeetCode—234. 回文链表

2025/3/12 22:12:34 来源:https://blog.csdn.net/weixin_44382896/article/details/141302881  浏览:    关键词:【Hot100】LeetCode—234. 回文链表

目录

  • 1- 思路
    • 快慢指针+链表拆分+反转链表
  • 2- 实现
    • ⭐234. 回文链表——题解思路
  • 3- ACM 实现


  • 原题连接:234. 回文链表

1- 思路

快慢指针+链表拆分+反转链表

思路
①将链表拆分前后两个部分——>找拆分点②反转后面部分③根据反转结果,同时利用两个指针遍历

  • ① 找拆分点:快慢指针
    • 利用快慢指针,满指针的 next 就是 后半部分的头指针
  • ② 反转链表
    • 递归反转后半部分
  • ③ 遍历判断
    • 依次同时移动两个指针判断

2- 实现

⭐234. 回文链表——题解思路

在这里插入图片描述

/*** 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 endA = endOfA(head);boolean res = true;ListNode headB = reverseL(endA.next);ListNode curA = head;ListNode curB = headB;while(res && curB!=null){if(curA.val != curB.val){res = false;}curA = curA.next;curB = curB.next;}// 恢复 B reverseL(headB);return res;}public ListNode endOfA(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;}public ListNode reverseL(ListNode head){if(head==null || head.next==null){return head;}ListNode cur = reverseL(head.next);head.next.next = head;head.next = null;return cur;}
}

3- ACM 实现

public class isPalindrome {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public static boolean isP(ListNode head){ListNode endA = endOfA(head);// 反转ListNode headB = reverseL(endA.next);ListNode curA = head;ListNode curB = headB;boolean res = true;while(curB!=null){if(curA.val != curB.val){res = false;}curA = curA.next;curB = curB.next;}return res;}private static ListNode endOfA(ListNode head){ListNode slow = head;ListNode fast = head;while(fast.next!=null && fast.next.next!=null){slow = slow.next;fast = fast.next;}return slow;}private static ListNode reverseL(ListNode head){if(head == null || head.next==null){return head;}ListNode cur = reverseL(head.next);head.next.next = head;head.next = null;return cur;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入链表长度");int n = sc.nextInt();ListNode head = null,tail=null;for(int i = 0 ; i < n;i++){ListNode nowNode  = new ListNode(sc.nextInt());if(head==null){head = nowNode;tail = nowNode;}else{tail.next = nowNode;tail = nowNode;}}System.out.println("结果是"+isP(head));}
}

版权声明:

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

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

热搜词