题目

image.png

思路

  • 思路一:通过快慢指针找到中点,然后使用栈把后半部分保存。再通过出栈跟前一半进行比较,判断是否为回文链表
  • 思路二:通过计算模拟hash值来判断是否回文
  • 思路三:通过快慢指针找到中点,将后半部分逆转,再判断前一部分和后一部分是否一致

代码

  1. public boolean isPalindrome(ListNode head) {
  2. if(head == null) return true;
  3. ListNode fast = head, slow = head, end = null;
  4. boolean flag = true;
  5. while(fast != null) {
  6. if(fast.next == null) {
  7. fast = fast.next;
  8. flag = false;
  9. } else {
  10. fast = fast.next.next;
  11. slow = slow.next;
  12. }
  13. }
  14. end = slow;
  15. fast = head;
  16. if(!flag) slow = slow.next;
  17. Stack<ListNode> stack = new Stack<>();
  18. while(slow != null) {
  19. stack.push(slow);
  20. slow = slow.next;
  21. }
  22. while(!stack.isEmpty() && !fast.equals(end)) {
  23. if(fast.val == stack.pop().val) {
  24. fast = fast.next;
  25. }else return false;
  26. }
  27. if(fast.equals(end) && stack.size() == 0) return true;
  28. return false;
  29. }
  30. public boolean isPalindrome(ListNode head) {
  31. float s1 = 0,s2 = 0,t = 1;
  32. while(head != null) {
  33. s1 = s1*10 + head.val;
  34. s2 = s2 + t*head.val;
  35. t = t*10;
  36. head = head.next;
  37. }
  38. return s1 == s2;
  39. }
  40. //思路三
  41. public boolean isPalindrome(ListNode head) {
  42. if (head == null) return true;
  43. ListNode fast = head, slow = head;
  44. while (fast != null && fast.next != null) {
  45. slow = slow.next;
  46. fast = fast.next == null ? fast.next : fast.next.next;
  47. }
  48. ListNode prev = null;
  49. while (slow != null) {
  50. ListNode t = slow.next;
  51. slow.next = prev;
  52. prev = slow;
  53. slow = t;
  54. }
  55. while (head != null && prev != null) {
  56. if (head.val != prev.val) return false;
  57. head = head.next;
  58. prev = prev.next;
  59. }
  60. return true;
  61. }

回文链表