image.png

    1. class Solution {
    2. public boolean isPalindrome(ListNode head) {
    3. if(head==null)
    4. return true;
    5. //先找到中点
    6. ListNode s=head;
    7. ListNode f=head;
    8. Stack<ListNode> stack=new Stack<>();
    9. while(f!=null&&f.next!=null){ //快慢指针,当快指针到末尾的时候,慢指针就到了中点
    10. s=s.next;
    11. f=f.next.next;
    12. }
    13. /*while(s!=null){
    14. stack.push(s);
    15. s=s.next;
    16. }
    17. while(!stack.isEmpty()){
    18. if(head.val==stack.pop().val){
    19. head=head.next;
    20. }else{
    21. return false;
    22. }
    23. }
    24. return true;*/
    25. //中点后面的节点反转
    26. ListNode q = s.next;
    27. s.next = null;
    28. while (q != null) {
    29. ListNode r = q.next;
    30. q.next = s;
    31. s = q;
    32. q = r;
    33. }
    34. //进行匹配
    35. while (head != null && s != null) {
    36. if (head.val != s.val) { //如果有一个匹配不成功,就返回false
    37. return false;
    38. }
    39. head = head.next;
    40. s = s.next;
    41. }
    42. return true; //当全部都匹配成功的时候,就返回true
    43. }
    44. }