LeetCode 234. 回文链表

朴灿烈づ我的快乐病毒、 2022-11-01 04:26 253阅读 0赞

在这里插入图片描述

  1. //解法一:fast走两格,slow走一个,slow走的时候进行反转前半部分链表
  2. /**
  3. * Definition for singly-linked list.
  4. * public class ListNode {
  5. * int val;
  6. * ListNode next;
  7. * ListNode() {}
  8. * ListNode(int val) { this.val = val; }
  9. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  10. * }
  11. */
  12. class Solution {
  13. public boolean isPalindrome(ListNode head) {
  14. if(head == null || head.next == null)
  15. return true;
  16. ListNode slow = head;
  17. ListNode fast = head;
  18. ListNode pre = null;
  19. while(fast != null && fast.next != null){
  20. fast = fast.next.next;
  21. ListNode tmp = slow.next;
  22. slow.next = pre;
  23. pre = slow;
  24. slow = tmp;
  25. }
  26. if(fast != null)//长度为奇数fast会停在最后一个节点,slow此时是后半部分未反转的头节点,为了使得数量一致,slow需要后一一个节点
  27. slow = slow.next;
  28. while(pre != null && slow != null){
  29. if(pre.val != slow.val)
  30. return false;
  31. slow = slow.next;
  32. pre = pre.next;
  33. }
  34. return true;
  35. }
  36. }
  37. //解法二:花式递归 玩不懂。。。
  38. //https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/
  39. class Solution {
  40. private ListNode frontPointer;
  41. private boolean recursivelyCheck(ListNode currentNode) {
  42. if (currentNode != null) {
  43. if (!recursivelyCheck(currentNode.next)) {
  44. return false;
  45. }
  46. if (currentNode.val != frontPointer.val) {
  47. return false;
  48. }
  49. frontPointer = frontPointer.next;
  50. }
  51. return true;
  52. }
  53. public boolean isPalindrome(ListNode head) {
  54. frontPointer = head;
  55. return recursivelyCheck(head);
  56. }
  57. }

发表评论

表情:
评论列表 (有 0 条评论,253人围观)

还没有评论,来说两句吧...

相关阅读