这道题容易想到的思路是:遍历链表存入list中,判断list是否回文
但综合类解法为:用快慢指针找到链表的中间位置,然后将链表从中间断开,将后半部分翻转,与前半部分比较。
class Solution { public boolean isPalindrome(ListNode head) { List<Integer> list = new LinkedList<>(); while(head != null){ list.add(head.val); head = head.next; } int i = 0; int j = list.size()-1; while(i<j){ if(!list.get(i).equals(list.get(j))) //list中两个元素相等判断方法equals return false; i++; j--; } return true; } }
class Solution { public boolean isPalindrome(ListNode head) { if(head == null)return true; ListNode p1 = head; ListNode mid = slowfast(head); ListNode second = reverse(mid); ListNode p2 = second; boolean res = true; while(true && p2 != null){ if(p1.val != p2.val) res = false; p1 = p1.next; p2 = p2.next; } mid.next = reverse(second); return res; } //快慢指针法 public ListNode slowfast(ListNode head){ ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } //链表反转 public ListNode reverse(ListNode head){ ListNode pre = null; ListNode cur = head; while(cur != null){ ListNode last = cur.next; cur.next = pre; pre = cur; cur = last; } return pre; } }